有没有办法在Kotlin中判断一个lazy val是否已经被初始化,而不需要在进程中初始化它?
例如,如果我有一个lazy val,查询它是否为null将实例化它
val messageBroker: MessageBroker by lazy { MessageBroker() }
if (messageBroker == null) {
// oops
}
我可以潜在地使用第二个变量,但这看起来很混乱。
private var isMessageBrokerInstantiated: Boolean = false
val messageBroker: MessageBroker by lazy {
isMessageBrokerInstantiated = true
MessageBroker()
}
...
if (!isMessageBrokerInstantiated) {
// use case
}
有没有什么很吸引人的方式来确定这一点,比如if (Lazy(messageBroker).isInstantiated())
相关(但不相同):How to check if a "lateinit" variable has been initialized?
发布于 2017-03-01 14:12:04
有一种方法,但您必须访问由lazy {}
返回的委托对象
val messageBrokerDelegate = lazy { MessageBroker() }
val messageBroker by messageBrokerDelegate
if(messageBrokerDelegate.isInitialized())
...
isInitialized
是接口Lazy<T>
上的一个公共方法,这里是docs。
发布于 2018-05-25 23:04:18
测试lazy属性是否足够简单:
import kotlin.reflect.KProperty0
import kotlin.reflect.jvm.isAccessible
val KProperty0<*>.isLazyInitialized: Boolean
get() {
// Prevent IllegalAccessException from JVM access check
isAccessible = true
return (getDelegate() as Lazy<*>).isInitialized()
}
…但是,您可以使引用属性而无需初始化它变得更加容易:
/**
* Returns the value of the given lazy property if initialized, null
* otherwise.
*/
val <T> KProperty0<T>.orNull: T?
get() = if (isLazyInitialized) get() else null
现在,您可以执行以下操作:
private val myList by lazy {
mutableSetOf<String>()
}
fun add(str: String) {
// Create the list if necessary
myList += str
}
fun remove(str: String) {
// Don't create the list
::myList.orNull?.remove(str)
}
fun clear() {
// Don't create the list
::myList.orNull?.clear()
}
https://stackoverflow.com/questions/42522739
复制相似问题