Fix 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.

Handle Kotlin Compilation Error Null can not be a value of a non-null type String - Kotlin Tutorial - www.tutorialkart.com

Handle Kotlin Compilation Error

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.
  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.

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.