有没有办法确定是否在Kotlin中初始化了一个懒惰的val,而没有在过程中对其进行初始化?
例如,如果我有一个懒惰的val,查询它是否为空将实例化它
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?
最佳答案
有一种方法,但是您必须访问lazy {}
返回的委托(delegate)对象:
val messageBrokerDelegate = lazy { MessageBroker() }
val messageBroker by messageBrokerDelegate
if(messageBrokerDelegate.isInitialized())
...
isInitialized
是Lazy<T>
接口(interface)上的公共(public)方法,这是docs。