As Kotlin doesn't allow for implicit null values/variables, was KotlinNullPointerException
introduced to explicitly denote NPE
caused by !!
? Is that the only purpose of this child class of NullPointerException
?
There is no real difference between a KotlinNullPointerException
and JavaNullPointerException
.
Here is how:
KotlinNullPointerException
is an open
class that extends NullPointerException
Now this NullPointerException
is a typealias
of java.lang.NullPointerException
.
public open class KotlinNullPointerException : NullPointerException {
constructor()
constructor(message: String?) : super(message)
}
This is a line extracted from TypeAlias.Kt
@SinceKotlin("1.1") public actual typealias NullPointerException = java.lang.NullPointerException
Now, if we see the declaration of java.lang.NullPointerException
, we are taken to a Java.lang
class that extends 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);
}
}
In Kotlin, to make some declaration of nullable type, you have to explicitly allow it by appending ?
at the end of declaration type. Example:
var nullableString: String? = null
This is a simple way of saying that this variable could be null anytime, so if you try to access this variable from any part of your code, it will throw error and will force you to take measures to prevent NPE
either using !!
(crash if null) or ?
(skip if null).
It's just a way to make it look more like 'Kotlin'.
As of version 1.3, Kotlin throws KotlinNullPointerException
only in case of a failed !!
operator check. This distinguishes it from the other cases where NullPointerException
can be thrown, for example, when accessing non-initialized members during class construction.
Note, however, that there are plans to remove this distinction in Kotlin 1.4: all such failed checks will throw just NullPointerException
, so its inheritor KotlinNullPointerException
will become unused. You can read more about that in the announce blog post of 1.3.50 version release: https://blog.jetbrains.com/kotlin/2019/08/kotlin-1-3-50-released/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With