由于Kotlin不允许使用隐式的空值/变量,因此引入了
KotlinNullPointerException
以明确表示由!!
引起的NPE
。这个子类的唯一目的是吗?KotlinNullPointerException
以明确表示由!!
引起的NPE
。这个子类的唯一目的是吗?KotlinNullPointerException
和JavaNullPointerException
之间没有实质性的区别。
下面是原因:
KotlinNullPointerException
是一个继承自NullPointerException
的open
类。现在这个NullPointerException
是java.lang.NullPointerException
的typealias
。
public open class KotlinNullPointerException : NullPointerException {
constructor()
constructor(message: String?) : super(message)
}
这是从 TypeAlias.Kt
中提取出来的一行代码。
@SinceKotlin("1.1") public actual typealias NullPointerException = java.lang.NullPointerException
java.lang.NullPointerException
的声明,我们会进入一个扩展了RuntimeException
的Java.lang
类。public
class NullPointerException extends RuntimeException {
private static final long serialVersionUID = 5162710183389028792L;
/**
* Constructs a {@code NullPointerException} with no detail message.
*/
public NullPointerException() {
super();
}
/**
* Constructs a {@code NullPointerException} with the specified
* detail message.
*
* @param s the detail message.
*/
public NullPointerException(String s) {
super(s);
}
}
在 Kotlin 中,如果要声明一个可空类型,必须在类型声明的末尾显式添加 ?
。例如:
var nullableString: String? = null
!!
运算符检查失败时抛出KotlinNullPointerException
。这与其他情况不同,例如在类构造期间访问未初始化成员时可能会引发NullPointerException
。NullPointerException
,因此其继承者KotlinNullPointerException
将变得无用。您可以在1.3.50版本发布的博客文章中了解更多信息:https://blog.jetbrains.com/kotlin/2019/08/kotlin-1-3-50-released/