Kotlin 中的实例化类仍然可能为 null。为什么?

Amb*_*ran 1 kotlin

问题很简单:在 Kotlin 中,当我arguments使用 a实例化片段时Bundle(),系统仍然需要使用 来保证参数对象!!。现在arguments应该绝对不是空的,对吧?那为什么需要呢?

这是代码:

private fun openPinCodeFragment(mode: PinView.Mode) {
    currentFragment = PinCodeFragment()
    currentFragment?.run {
        arguments = Bundle()
        arguments!!.putSerializable(MODE, mode)
    }
    openFragment(currentFragment)
}
Run Code Online (Sandbox Code Playgroud)

如果我删除!!那么:

在此处输入图片说明

Ada*_*old 5

您正在设置在此范围之外定义的变量的值(arguments在您的代码中不可见的声明)。

无论您分配什么,它都可能在代码执行到达下一行时更改为null另一个值Thread,这就是您必须使用!!here 的原因。我建议arguments在本地范围内定义val或使其在其定义中不可为空。