本文介绍了如何执行伴随对象lateinit是初始化检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个Lateinit变量,我可以检查是否使用(this :: lateInitVar.isInitialized)对其进行了初始化,如 https中所示://stackoverflow.com/a/47860466/3286489
If I have a lateinit variable, I could check is it initialized using (this::lateInitVar.isInitialized), as shown in https://stackoverflow.com/a/47860466/3286489
但是如果变量是伴随对象,该怎么办?
However if the variable is a companion object, how could I do so?
例如
class MyClass {
companion object {
lateinit var myGlobalLateInit: String
}
lateinit var myLocalLateInit: String
fun settingVariable() {
if (!this::myLocalLateInit.isInitialized) {
myLocalLateInit = "I am set"
}
if (!MyClass::myGloablLateInit.isInitialized) { // This line will error out. How could I set it?
myGloablLateInit = "I am set"
}
}
}
推荐答案
您可以将其提取到伴随对象内部的函数中:
You could extract it into a function inside the companion object:
class MyClass {
companion object {
lateinit var myGlobalLateInit: String
fun isMyGlobalLateInitInitialized() = ::myGlobalLateInit.isInitialized
}
fun settingVariable() {
if (!isMyGlobalLateInitInitialized()) {
myGlobalLateInit = "I am set"
}
}
}
这篇关于如何执行伴随对象lateinit是初始化检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!