Generics Kotlin可分配泛型惰性可空性问题
我想从数据库加载数据(在带Room的Android上) 我不能使用惰性委托,因为我需要在存储库中而不是直接在POJO中分配值 我希望有一个函数以Generics Kotlin可分配泛型惰性可空性问题,generics,kotlin,lazy-loading,Generics,Kotlin,Lazy Loading,我想从数据库加载数据(在带Room的Android上) 我不能使用惰性委托,因为我需要在存储库中而不是直接在POJO中分配值 我希望有一个函数以fun get():T的形式获取我的值,T可以为null 我面临的问题是,如果我想要一个返回T和一个T,我需要两个函数?但我只想要一个。我的可分配延迟代码: sealed class LazyDBLoad<T, D> { abstract fun getNullable() : T? abstract fun get(): T
fun get():T
的形式获取我的值,T可以为null
我面临的问题是,如果我想要一个返回T和一个T,我需要两个函数?但我只想要一个。我的可分配延迟代码:
sealed class LazyDBLoad<T, D> {
abstract fun getNullable() : T?
abstract fun get(): T
companion object {
fun <T, D> of(dependency: D, onLoad: (D) -> T) : LazyDBLoad<T, D> {
return LazyDBLoadImpl(dependency, onLoad)
}
}
private class LazyDBLoadImpl<T, D>(
private val dependency: D,
private val onLoad: (D) -> T) : LazyDBLoad<T, D>(){
private var wasLoaded = false
private var loaded: T? = null
override fun getNullable(): T? {
if (!wasLoaded) {
wasLoaded = true
loaded = onLoad(dependency)
}
return loaded
}
override fun get(): T {
return getNullable() ?: throw Exception("Not Nullable was null")
}
}
}
密封类懒散负载{
抽象乐趣getNullable():T?
抽象趣味get():T
伴星{
(依赖项:D,onLoad:(D)->T)的乐趣:懒散的加载{
返回LazyDBLoadImpl(依赖项,onLoad)
}
}
私有类LazydLoadImpl(
私有val依赖项:D,
private val onLoad:(D)->T:LazyDBLoad(){
私有变量wasload=false
加载的私有变量:T?=null
重写fun getNullable():T{
如果(!已加载){
wasload=true
已加载=已加载(依赖项)
}
返回装载
}
重写fun get():T{
return getNullable()?:抛出异常(“notNullable为null”)
}
}
}
用法示例:
var accessCount: Int = 0
val databaseResult: Int
get() = if (accessCount < 1) {accessCount = accessCount.inc();4711} else {println("Too many accesses");-1}
fun main() {
val dependency = Any()
val lazyProperty: LazyDBLoad<Int, Any> = LazyDBLoad.of(dependency) {
return@of databaseResult
}
val value: Int? = lazyProperty.getNullable()
val value2: Int = lazyProperty.get()
val lazyPropertyNull: LazyDBLoad<Int?, Any> = LazyDBLoad.of(dependency){null}
val get = lazyPropertyNull.getNullable() //works
val get2 = lazyPropertyNull.get() // Error but because of types no compile error
}
var accessCount:Int=0
val数据库结果:Int
get()=if(accessCount<1){accessCount=accessCount.inc();4711}else{println(“太多访问”);-1}
主要内容(){
val dependency=Any()
val lazyProperty:LazyDBLoad=LazyDBLoad.of(依赖项){
return@of数据库结果
}
val值:Int?=lazyProperty.getNullable()
val value2:Int=lazyProperty.get()
val lazyPropertyNull:LazyDBLoad=LazyDBLoad.of(依赖项){null}
val get=lazyPropertyNull.getNullable()//有效
val get2=lazyPropertyNull.get()//错误,但由于类型的原因,没有编译错误
}
如果您只是在getNullable()
为null时抛出异常,为什么需要get()
函数?只需删除它,将getNullable()
重命名为get()
,然后使用代码>运算符,如果您不需要可为空的值。@ardenit公平点,但我想要一个解决方案,其中泛型in“of”函数决定输出类型。@ardenit thx,我认为太复杂了。现在我可以像var-lazyProp:LazyDBLoad?=null val actualProp:Int get()=lazyProp!!。获取()代码>