Kotlin:检查是否已初始化惰性val [英] Kotlin: Check if lazy val has been initialised
问题描述
有没有办法确定是否在Kotlin中初始化了一个懒惰的val,而没有在过程中对其进行初始化?
Is there a way to tell if a lazy val has been initialised in Kotlin without initialising it in the process?
例如,如果我有一个惰性val,则查询它是否为null会实例化它
eg if I have a lazy val, querying if it is null would instantiate it
val messageBroker: MessageBroker by lazy { MessageBroker() }
if (messageBroker == null) {
// oops
}
我可能会使用第二个变量,但这似乎很麻烦.
I could potentially use a second variable, but that seems messy.
private var isMessageBrokerInstantiated: Boolean = false
val messageBroker: MessageBroker by lazy {
isMessageBrokerInstantiated = true
MessageBroker()
}
...
if (!isMessageBrokerInstantiated) {
// use case
}
是否有一些性感的方法来确定这一点,例如if (Lazy(messageBroker).isInstantiated())
?
Is there some sexy way of determining this, like if (Lazy(messageBroker).isInstantiated())
?
相关(但不相同):如何检查是否有"lateinit"变量已初始化?
推荐答案
有一种方法,但是您必须访问lazy {}
返回的委托对象:
There is a way, but you have to access the delegate object which is returned by lazy {}
:
val messageBrokerDelegate = lazy { MessageBroker() }
val messageBroker by messageBrokerDelegate
if(messageBrokerDelegate.isInitialized())
...
isInitialized
是接口Lazy<T>
上的公共方法,这是
isInitialized
is a public method on interface Lazy<T>
, here are the docs.
这篇关于Kotlin:检查是否已初始化惰性val的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!