Consider the following code:
Example
fun main(args: Array<String>) {
maybeWriteMessage()
}
fun maybeWriteMessage(message: String? = null) {
writeMessage(message!!)
}
fun writeMessage(message: String) {
println("Hello World")
}
Output
Exception in thread "main" kotlin.KotlinNullPointerException at com.series0ne.ApplicationKt.maybeWriteMessage(Application.kt:8) at com.series0ne.ApplicationKt.maybeWriteMessage$default(Application.kt:7) at com.series0ne.ApplicationKt.main(Application.kt:4)
This is because I'm passing message!!
(null, damn it!) to a non-nullable parameter, however the parameter is never accessed.
Question
Why does Kotlin forcibly throw KotlinNullPointerException
even when the null reference isn't accessed?
There are some best practices to avoid NullPointerException in Java that are mentioned some of them as below: Basically, Kotlin null safety has been proposed to eliminate NullPointerException form the code. NullPointerException can just only possible on following situations:
Basically, Kotlin null safety is proposed to eliminate NullPointerException form the code. NullPointerException can just only possible on following situations: Throw NullPointerException () as a forceful call Using external java code as Kotlin, which means Java interoperability.
If the @Nullable and @NotNull annotations are being used properly, both Java and Android ones, Kotlin will be able to work seamlessly with them and figure out when a variable is null and when not. Many parts of the Android framework are already annotated correctly, so this is a huge advantage to working with Kotlin.
It first started when I heard Kotlin eradicates the possibility of the dreaded NullPointerException (false information, but hey it was something to get excited about). Then I saw how elegant it was to model information using the data class and as an RxJava user I found sealed classes an easy way to model streams of data.
message: String?
is indicating that message
may or may not be null
.
Since your function maybeWriteMessage
has a default value of null
for message
and you are calling maybeWriteMessage()
without specifying message
- the default value (null
) will be used when calling writeMessage(message!!)
.
As written in the documentation the !!
-operator throws an exception when the value is null
.
One way to trigger writeMessage
safely would be to use .let
:
fun maybeWriteMessage(message: String? = null) {
message?.let {
writeMessage(it)
}
}
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