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())
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)