Kotlin Null Safety

Kotlin null safety is a procedure to eliminate the risk of null reference from the code. Kotlin compiler throws NullPointerException immediately if it found any null argument is passed without executing any other statements.

Kotlin's type system is aimed to eliminate NullPointerException form the code. NullPointerException can only possible on following causes:

  • An forcefully call to throw NullPointerException();
  • An uninitialized of this operator which is available in a constructor passed and used somewhere.
  • Use of external java code as Kotlin is Java interoperability.

Kotlin Nullable Types and Non-Nullable Types

Kotlin types system differentiates between references which can hold null (nullable reference) and which cannot hold null (non null reference). Normally,types of String are not nullable. To make string which holds null value, we have to explicitly define them by putting a ? behind the String as: String?

Nullable Types

Nullable types are declared by putting a ? behind the String as:

Kotlin example of nullable types

Output:

null

Non Nullable Types

Non nullable types are normal strings which are declared as String types as:

What happens when we assign null value to non nullable string?

Output:

It will generate a compile time error.

Error:(3, 11) Kotlin: Null can not be a value of a non-null type String

Checking for null in conditions

Kotlin's If expression is used for checking condition and returns value.

Output:

str is : Hello
str length is : 5
str is : null
b length is : -1





Latest Courses