且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将可为空的类型转换为其不可为空的类型?

更新时间:2022-02-08 18:30:14

您需要像这样的双感叹号:

You need double exclamation mark like so:

val bar = makeNewBar(foo.name!!)

无效安全"部分中所述:>

As documented in Null Safety section:

第三个选项适用于NPE爱好者.我们可以写b !! 返回b的非空值(例如,在我们的示例中为String)或抛出 如果b为null,则为NPE:

The third option is for NPE-lovers. We can write b!!, and this will return a non-null value of b (e.g., a String in our example) or throw an NPE if b is null:

val l = b!!.length 

因此,如果您想要NPE,可以拥有它,但是必须明确要求它,并且它不会出现在NPE之外. 蓝色.

Thus, if you want an NPE, you can have it, but you have to ask for it explicitly, and it does not appear out of the blue.