首页 > 解决方案 > KotlinNullPointerException 和 Java 的 NullPointerException 有什么区别

问题描述

由于 Kotlin 不允许隐式空值/变量,因此KotlinNullPointerException引入明确表示NPE!!? 这是这个子类的唯一目的NullPointerException吗?

标签: kotlinnullpointerexception

解决方案


KotlinNullPointerExceptiona和之间没有真正的区别JavaNullPointerException

方法如下:

KotlinNullPointerException是一个open扩展的类NullPointerException现在这NullPointerException是一个typealiasof java.lang.NullPointerException

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,我们将被带到一个Java.lang扩展的类RuntimeException

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

这是一种简单的说法,即此变量随时可能为空,因此如果您尝试从代码的任何部分访问此变量,它将引发错误并迫使您采取措施防止NPE使用!!(如果为空则崩溃)或?(如果为 null,则跳过)。这只是让它看起来更像“Kotlin”的一种方式。


推荐阅读