我正在用 Kodein 试用 Kotlin,在我目前的项目中,我在 Kodein 中获得了 NPE,但我不知道为什么。
我有一些数据类和匹配的存储库,它们提供了它们的列表:
data class Cat(val name: String)
data class Dog(val name: String)
interface Repository<T> {
val all: List<T>
}
interface CatRepository : Repository<Cat>
interface DogRepository : Repository<Dog>
这些存储库的实现当前由主类支持:
data class AnimalData(val cats: List<Cat>, val dogs: List<Dog>)
我为存储库创建了一个抽象基类:
abstract class AnimalDataRepository<T>(override val kodein: Kodein) : Repository<T>, KodeinAware {
private val animalData: AnimalData by instance()
abstract val property: (AnimalData) -> List<T>
override val all: List<T> = animalData.let(property)
}
因此存储库实现如下所示:
class CatRepositoryImpl(override val kodein: Kodein) : CatRepository, AnimalDataRepository<Cat>(kodein) {
override val property = AnimalData::cats
}
设置并运行:
fun main() {
val kodein = Kodein {
bind<AnimalData>() with singleton { AnimalData(listOf(Cat("Tigger")), listOf(Dog("Rover"))) }
bind<CatRepository>() with singleton { CatRepositoryImpl(kodein) }
}
val catRepository: CatRepository by kodein.instance()
println(catRepository.all)
}
导致 Kotlin 内部的 NPE:
Exception in thread "main" java.lang.NullPointerException
at org.kodein.di.KodeinAwareKt$Instance$1.invoke(KodeinAware.kt:176)
at org.kodein.di.KodeinAwareKt$Instance$1.invoke(KodeinAware.kt)
at org.kodein.di.KodeinProperty$provideDelegate$1.invoke(properties.kt:42)
at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
at AnimalDataRepository.getAnimalData(KodeinExample.kt)
at AnimalDataRepository.<init>(KodeinExample.kt:27)
at CatRepositoryImpl.<init>(KodeinExample.kt:30)
at KodeinExampleKt$main$kodein$1$2.invoke(KodeinExample.kt:40)
at KodeinExampleKt$main$kodein$1$2.invoke(KodeinExample.kt)
at org.kodein.di.bindings.Singleton$getFactory$1$1$1.invoke(standardBindings.kt:130)
...
我不清楚为什么会发生这种情况。它与使用“属性”映射lamba有关AnimalDataRepository
,因为当我不使用它时它工作正常。
完整代码作为要点:https ://gist.github.com/RoToRa/65d664d2d7497ddbf851a1be019f631d