如何通过扩展函数编写自己的
How to write my own by extension function
我有一个这样的默认函数:
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()
有关详细信息,请参阅 Delegated properties doc
我有一个这样的默认函数:
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()
有关详细信息,请参阅 Delegated properties doc