Skip to content
DeveloperMemos

Exploring Null Checking with Kotlin's 'when' Expression

Kotlin, Null Checking, Programming Language1 min read

In Kotlin, the when expression is a powerful construct that allows you to replace complex if-else chains with more concise and readable code. When dealing with nullable values, you can use when to handle different cases, including null values.

Basic Usage of when Expression

Before we discuss null checking, let's review the basic usage of when. The general syntax is as follows:

1when (variable) {
2 value1 -> // do something
3 value2 -> // do something else
4 // ...
5 else -> // default case
6}

In this structure:

  • variable represents the value you want to check.
  • value1, value2, etc., are the possible values you're interested in.
  • The else branch handles any other cases not explicitly covered.

Null Checking with when

To incorporate null checks into a when expression, consider the following scenarios:

  1. Checking for Null or Empty Strings

Suppose you have a nullable string (myString) and want to handle three cases:

  • If myString is "1", print "1".
  • If myString is "2", print "2".
  • If myString is null or empty, print "null or empty".

You can achieve this using the following code:

1when {
2 myString == "1" -> print("1")
3 myString == "2" -> print("2")
4 myString.isNullOrEmpty() -> print("null or empty")
5 else -> print("None of them")
6}

The isNullOrEmpty() function checks whether the string is either null or empty¹.

  1. Handling Nullable Booleans

If you're dealing with nullable booleans, you can use a similar approach:

1val b: Boolean? = // your boolean value (nullable)
2
3when (b) {
4 true -> // handle true case
5 false -> // handle false case
6 null -> // handle null case
7}
  1. Treating Null Differently from True or False

To treat null differently from true or false, use the following:

1when (bool) {
2 null -> println("null")
3 true -> println("foo")
4 false -> println("bar")
5}

In Closing

Kotlin's when expression provides a flexible way to handle different cases, including null values. By combining it with functions like isNullOrEmpty(), you can write concise and expressive code.

Remember to adapt these examples to your specific use cases, and happy coding! 🚀