如何检查是否有"lateinit"?变量已初始化? [英] How to check if a "lateinit" variable has been initialized?
本文介绍了如何检查是否有"lateinit"?变量已初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有一种方法可以检查lateinit
变量是否已初始化.例如:
I wonder if there is a way to check if a lateinit
variable has been initialized. For example:
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
变量的初始化状态:
There is a lateinit
improvement in Kotlin 1.2 that allows to check the initialization state of lateinit
variable directly:
lateinit var file: File
if (this::file.isInitialized) { ... }
请参见 JetBrains博客或 KEEP提案.
更新:Kotlin 1.2已发布.您可以在此处找到lateinit
增强功能:
UPDATE: Kotlin 1.2 has been released. You can find lateinit
enhancements here:
- Checking whether a lateinit var is initialized
- Lateinit top-level properties and local variables
这篇关于如何检查是否有"lateinit"?变量已初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文