— Kotlin, Null Checking, Programming Language — 1 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.
when
ExpressionBefore we discuss null checking, let's review the basic usage of when
. The general syntax is as follows:
1when (variable) {2 value1 -> // do something3 value2 -> // do something else4 // ...5 else -> // default case6}
In this structure:
variable
represents the value you want to check.value1
, value2
, etc., are the possible values you're interested in.else
branch handles any other cases not explicitly covered.when
To incorporate null checks into a when
expression, consider the following scenarios:
Suppose you have a nullable string (myString
) and want to handle three cases:
myString
is "1"
, print "1"
.myString
is "2"
, print "2"
.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¹.
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 case5 false -> // handle false case6 null -> // handle null case7}
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}
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! 🚀