gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:04:14 27 4
gpt4 key购买 nike

问题很简单:
在Kotlin中,当我用arguments实例化一个片段Bundle()时,系统仍然需要使用!!来保证arguments对象的安全。 arguments现在绝对应该不为空,对吗?那么为什么需要这样做呢?

这是代码:

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

如果我删除了 !!,则:

enter image description here

最佳答案

您正在设置在此范围之外定义的变量的值(在代码中看不到arguments的声明)。
无论您分配什么,它都可能在代码执行到达下一行时又被另一个null更改为Thread值的时间,这就是为什么您必须在此处使用!!的原因。我建议使用arguments在本地范围内定义val或使其在定义中不可为空。

关于kotlin - Kotlin中的实例化类仍可能为null。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58076482/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com