Note: 原创,非翻译。
What is “A trick about non-nullable type in Kotlin?”
The trick is that: "non-nullable type isn’t always being non-nullable at complie time."
As well known, a non-nullable type can’t be assigned with a null at compile time. If you force to run, your app will be failed at compile time. But Is there a way to around this constraint? Yes, there is.
Because you can compile Kotlin code with Java and Java doesn’t have a platform type called non-nullable. So that, you can pass a non-nullable type var as paramter into a Java method in which assign a null to it and return to the non-nullable var in Kotlin.
Having said that, your app still will throw an exception eventually but that will happen at runtime not at compile time. If so, the non-nullable type will lose it’s function(It’s better to detect a NullPointerExecption at compile time). Now, Let’s see how to concrete it:
// Define a non-nullable type var.
var test: String = ""
// Assign a null to a non-nullable type var from Java code.
test = NotificationUtil.test(test)
public class NotificationUtil {
public static String test(String test) {
test = null;
return test;
}
}
What we should do for it ? To avoid a NullPointerExecption thrown at runtime?
- Be careful when you assign a value to a non-nullable type var from Java code.
- It’s better to check value whether it’s null from java code, before assigning it to a non-nullable type var.
- The less java code you compiled with Kotlin, The less problems you will encounter.
本文探讨了Kotlin中非空类型的一个鲜为人知的特性:尽管非空类型理论上不能被赋空值,但通过Java代码可以绕过这一限制,导致运行时NullPointerException。文章提供了示例代码,并建议在从Java代码赋值给非空类型变量前进行空值检查。
1763

被折叠的 条评论
为什么被折叠?



