我想知道是否有办法检查 lateinit
变量是否已初始化。例如:
class Foo() {
private lateinit var myFile: File
fun bar(path: String?) {
path?.let { myFile = File(it) }
}
fun bar2() {
myFile.whateverMethod()
// May crash since I don't know whether myFile has been initialized
}
}
最佳答案
在 Kotlin 1.2 中有一个 lateinit
改进,允许直接检查 lateinit
变量的初始化状态:
lateinit var file: File
if (this::file.isInitialized) { ... }
查看JetBrains blog上的公告或 KEEP proposal .
更新: Kotlin 1.2 已经发布。您可以在此处找到 lateinit
增强功能:
关于kotlin - 如何检查 "lateinit"变量是否已初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37618738/
相关文章:
kotlin - 如何将 Kotlin 的 MutableList 初始化为空 MutableLis
collections - Kotlin 的列表缺少 "add"、 "remove"、 map 缺少
kotlin - Kotlin中的var和val有什么区别?
properties - 使用 "by lazy"与 "lateinit"进行属性初始化
kotlin - 智能转换为 'Type' 是不可能的,因为 'variable' 是一个可变属性,
constants - "const"和 "val"有什么区别?