我有一个默认函数,如下所示:
fun <T> makeDefault(): Animal<T> = Animal<Nothing>(
name = "",
size = 0,
age = 0
)
我看到有by
运算符,它可以用于以下视图模型:
val model: MyViewModel by viewModels()
问题:如何为makeDefault()
创建这样的函数?
我想做的事:
val animal: Animal<Dog> by makeDefault()
您可以创建自己的委托,而不是扩展:
import kotlin.reflect.KProperty
class DefaultDelegate<T> {
private var created: Animal<T> = Animal<Nothing>(
name = "",
size = 0,
age = 0
)
operator fun getValue(thisRef: Any?, property: KProperty<*>): Animal<T> {
return created
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Animal<T>) {
created = value
}
}
然后使用它:
val animal: Animal<Dog> by DefaultDelegate()
有关更多信息,请参阅委托属性文档