kotlin - KotlinNullPointerException 和 Java 的 NullPointerException 有什么区别
问题描述
由于 Kotlin 不允许隐式空值/变量,因此KotlinNullPointerException
引入明确表示NPE
由!!
? 这是这个子类的唯一目的NullPointerException
吗?
解决方案
KotlinNullPointerException
a和之间没有真正的区别JavaNullPointerException
。
方法如下:
KotlinNullPointerException
是一个open
扩展的类NullPointerException
现在这NullPointerException
是一个typealias
of 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”的一种方式。
推荐阅读
- xamarin - Xamarin Google Maps 自定义消息弹出窗口
- maven - Makefile 运行 Maven 命令,但命令有“:”字符
- google-cloud-platform - 在 GCP 中创建 IAM 成员会引发错误 The size of the policy is too large
- react-native - 原生基础 FloatingLabel 焦点样式
- python - 如何使用 Python 更改或清除 Jira 中分辨率字段的值?
- wordpress - 无法导入磁盘空间不足。无法将内容写入文件。文件:/opt/bitnami/apps/wordpress/htdocs/wp-content/uploads 错误
- android - Android导航组件 - 如何“popBackStack”到不存在的目的地
- c - 如何在 gcc 或 g++ 编译器上使用编译不同的文件扩展名,例如“a.test”而不是“.c .cpp”
- .net - 如何安装 Sitecore 的试用版
- javascript - 如何在反应单页应用程序中隐藏 XHR 请求?