如何检查是否有“lateinit"变量是否已初始化? [英] How to check if a "lateinit" variable has been initialized?

查看:37
本文介绍了如何检查是否有“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:

这篇关于如何检查是否有“lateinit"变量是否已初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆