Kotlin Error: Null can not be a value of a non-null type String

This Kotlin Error occurs when a String variable is declared as non-nullable, but assigned a null value in the due course of program. We shall recreate the Error and provide necessary technique to handle the “Kotlin Error Null can not be a value of a non-null type String”

Let us first recreate the Error scenario using the following example, where we shall declare a variable str as non-nullable, but try to assign a null value.

example.kt

</>
Copy
fun main(args: Array){
    var str: String    // variable is declared as non-null
    str = "Hello !"
    println("Value of string is : $str")
	// try assigning a null value to non-null String variable
    str = null // this causes compilation error
    println("Value of string is : $str")
}

Output

Error:(6, 10) Null can not be a value of a non-null type String

How to Fix Kotlin Compilation Error: “Null can not be a value of a non-null type String”

There are two ways to handle this exception. They are :

1. Avoid assigning a null value to the non-nullable String variable.

example.kt

</>
Copy
fun main(args: Array){
    val str: String    // variable is declared as non-null
    str = "Hello !"
    println("Value of string is : $str")
}

Output

Compilation completed successfully
Value of string is : Hello !

2. Declare String variable to allow null using  ?  operator. In this scenario, caution has to be exercised to handle the most adverse exception ‘NullPointerException’. It is advised you follow the null safety in kotlin provided by Kotlin type system.

example.kt

</>
Copy
fun main(args: Array){
    var str: String?    // variable is declared as nullable
    str = "Hello !"
    println("Value of string is : $str")
    str = null
    println("Value of string is : $str")
}

Output

Compilation completed successfully
Value of string is : Hello !
Value of string is : null

Conclusion

In this Kotlin Tutorial, we have learnt how to handle the compilation error caused during assignment of null value to a non-null declared String variable.