Kotlin and Understanding NULL

There are some interesting concepts around how Kotlin handles the NULL value.

By default, Kotlin does not allow having a NULL value assigned to a variable.

Attempting to assign a NULL to a variable at the time the variable is being declared will result in an error at compile time.

val customerName: String = null (will result in a compile time error)

If you need to assign a NULL value to a variable when the variable is being declared, you must ensure that the variable is declared as being able to store a NULL value by putting a question mark (?) after the variables defined type.

val customerName: String? = null (no error at compile time, variable can contain a NULL)

Once a variable is defined as being nullable, you cannot then go and assign the value of this null variable to a non-nullable variable.

val customerName: String? = null
val memberName: String = customerName (will result in a compile time error)

if you first check that the value of the variable to be assigned is not NULL, then Kotlin will let you assign the variables value.

val customerName: String? = null

if (customerName!= null) {
val memberName: String = customerName

This way, only a non-null value will be assigned and any null value assignment would be discarded, creating it own problem with data consistency.

When using nullable variables, you can also use the ‘safe call’ operator. This operator ‘?.’ ensures that if the value in the variable is a null, then the function would not be called.


If you want to remove the restriction and checking performed on the nullable variable by the compiler you can use the ‘not null’ assertion.

val customerName: String? = null
val TrimVariable = customerName!!.trimStart() (will crash at run time)

The double exclamation marks after the variable name invoke the ‘not null’ assertion but come with a warning as you can now create a problem in your code with null assignment again, so be careful how you use this.