Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - why do I get a KotlinNullPointerException

Tags:

kotlin

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?

like image 827
Matthew Layton Avatar asked Jun 06 '18 09:06

Matthew Layton


People also ask

How to avoid NullPointerException in Java with Kotlin?

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:

What is null safety in Kotlin?

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.

Can Kotlin work with Java and Android?

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.

Why did you choose 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.


1 Answers

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)
    }
}
like image 52
d.felber Avatar answered Sep 17 '22 19:09

d.felber