
1. Overview
In this article, we will discuss the Kotlin case when with various examples. We can use when either as an expression or as a statement.
The When statement in Kotlin is equivalent to the switch statement in Java, C, and other languages. It is easier to maintain than nested if statements and improves readability by reducing repetitive code. The when more clearly expresses the logic of the code better.
Especially, use when statement to execute different code depending on the value of the expression. In short, it defines a conditional expression with multiple branches.
2. Kotlin when
2.1. when statement
The when expression matches its argument against all branches one by one until some branch condition satisfies the argument.
Let’s take a simple example for Kotlin when statement. Since x
is 1
, the first branch satisfies the statement and prints x == 1
.
Similar to the if statement, the branch can have a block of code enclosed by parenthesis like in the else branch below.
fun main() { val x = 1 when (x) { 1 -> print("x == 1") 2 -> print("x == 2") else -> { print("x is neither 1 nor 2") } } }
2.2. when expression
You can use Kotlin when as an expression. The value of the first matching branch becomes the value of the overall expression.
Let’s take the below example for when expression. Since the x
is 2, the when expression matches the first branch and returns 4
.
fun main() { val x = 1 val square = when (x) { 1 -> 1 2 -> 4 3 -> 9 else -> 0 } println(square) }
In the below example, each branch has a block of code. So the when expression will use the last statement in the block as the value and returns it.
fun main() { val x = 2 val square = when (x) { 1 -> { println("x == 1") 1 } 2 -> { println("x == 2") 4 } 3 -> { println("x == 3") 9 } else -> { println("Not applicable") 0 } } println(square) }
The else
branch is mandatory. But the compiler knows that you have covered all the cases with branch conditions, then it allows you to ignore the else branch. For example, with enum
and sealed
class which we will discuss in below sections.
3. When with repetitive code
To define the same behavior for multiple branches, you can combine their conditions in a single line with a comma.
fun main(args: Array<String>) { val day = "Mon" val dayType = when (day) { "Mon" -> "Working" "Tue" -> "Working" "Wed" -> "Working" "Thu" -> "Working" "Fri" -> "Working" "Sat" -> "Holiday" "Sun" -> "Holiday" else -> { print("Not a valid day") } } println(dayType) }
The above code contains a lot of repetitive common code across branches. So you can combine them in a single line separated by commas as below:
fun main() { val day = "Mon" val dayType = when (day) { "Mon", "Tue", "Wed", "Thu", "Fri" -> { println("This is a working day") "Working" } "Sat", "Sun "-> { println("Hurray! Today is a holiday") "Holiday" } else -> { print("Not a valid day") } } println(dayType) }
4. When with expressions as branch conditions
You can use expressions as branch conditions. In the below example, the first branch condition is an expression that evaluates to Int
.
Note that when argument and the result of the branch condition should be of the same type, meaning the x
argument in the when is Int
and the branch condition also evaluates to Int type.
fun main() { val x = 20 val y = "20" when (x) { y.toInt() -> print("X is equal to Y") else -> print("X is not equal to Y") } }
5. Kotlin when in range
You can also use in
or !in
a range with the branch condition. Kotlin in
is the shorthand for the operator contains.
In the below example, the when second condition satisfies as x 21 is not in the range and prints “x is outside the range
“.
fun main() { val x = 21 when (x) { in 1..10 -> print("x is in the range") !in 10..20 -> print("x is outside the range") else -> print("none of the above") } }
6. Kotlin when in collections
Similar to the range, you can also use in
or in!
a collection with the branch condition.
In the below example, validNumbers
collection contains the x
value 12
. So the first condition matches and prints x is valid
.
fun main() { val validNumbers = arrayOf(3, 6, 12) val x = 12 when (x) { in validNumbers -> print("x is valid") else -> print("none of the above") } }
7. Kotlin when is type
Similar to in or in! operators, you can also use the Kotlin is or is! type check operators to check whether the argument is of a particular type.
In the below example, the when expression takes the argument x of type Any
. The first branch condition checks whether the argument is of String type.
We are using contains
function on variable x
with no type casting inside the first branch block. Because the compiler tracks the result of the is operator check. If the is check is success, the compiler automatically casts the x
variable to String
. So subsequent invocations treat the variable x
as String
. Therefore, x.contains
will work with no cast.
fun contains(x: Any) : Boolean { return when(x) { is String -> x.contains("/") else -> false } } fun main() { println("String is a path: " +contains("/sub.txt")) }
8. Kotlin when boolean
You can also ignore the argument of when. In such cases, the branch conditions are only boolean expressions, and the condition that evaluates to true will execute.
In the below example, a
is 10
and the first branch condition evaluates to true
.
fun main() { val a = 10 val b = 20 when { a == 10 -> print("a is 10") b != 20 -> print("b is not 20") else -> print("none matches") } }
9. Kotlin when string startswith
As mentioned in the previous section, you can ignore the argument in when
and use any boolean expression in the branch condition.
String startsWith is a boolean expression that checks a String’s starting letter and returns true or false. You can use this function in the branch condition to execute different code based on the string’s prefix.
Let’s take the below example. The when statement doesn’t take any argument so branch condition are simply boolean expressions. We are using startsWith
to check the grade and execute the code accordingly.
Here, the grade variables starts with A character, so first branch condition evaluates to true and prints A in the console.
fun main() { val grade = "A grade" when { grade.startsWith('A') -> println("A") grade.startsWith('B') -> println("B") else -> println("Fail") } }
11. kotlin when equals
Similar to startsWith, you can also use equals function with the when.
In the below example, we validate motorObj
and userEntry
objects using equals function. The first branch condition satisfies and prints "User selected motor so proceed"
.
fun main() { val motorObj = "motor" val userEntry = "motor" when { motorObj.equals(userEntry) -> println("User selected motor so proceed") else -> println("No") } }
12. Kotlin when enum example
You can use enum variable as argument to your when expression as below. See enum article for more examples of enum with when.
fun getDirection(direction: Direction) { when(direction) { Direction.SOUTH -> println("South") Direction.NORTH -> println("North") Direction.WEST -> println("West") Direction.EAST -> println("East") } } enum class Direction { NORTH, SOUTH, EAST, WEST } fun main() { getDirection(Direction.NORTH) }
13. when kotlin string
You can pass String
as an argument to the when statement.
In the below example, we are passing the course
string as an argument to when statement. The when branch condition evaluates the string and execute code on match.
fun main() { val course = "CS" when (course) { "CS" -> { println("Computer science") } "IT"-> { println("Information technology") } else -> { print("Not from computer background") } } }
14. kotlin sealed class when
You can use sealed class sub types as an argument to the when statement.
If you know all the subtypes of a sealed class in advance, the compiler will allow you to ignore the else clause in the when expression.
Here, we know that there are exactly three subclasses available for Vehicle
sealed class. Since we are covering all the subclass conditions in when, there is no need to add an else clause here.
sealed class Vehicle data class Car(val brandName: String, val owner: String, val color: String): Vehicle() class Bike(val brandName: String, val owner: String, val color: String): Vehicle() class Tractor(val brandName: String, val owner: String, val color: String): Vehicle() fun eval(vehicle: Vehicle): String { return when(vehicle) { is Car -> "This is a car" is Bike -> "This is a bike" is Tracktor -> "This is a tractor" }
15. kotlin when two conditions
You can have any number of conditions – one or more in the when statement.
In the below example, we have two conditions. The else branch is not mandatory for when statement however mandatory if we use when as an expression. The below code uses when as a statement and else ignored.
fun main() { val a = 10 when(a) { 10 -> println("A is 10") 20 -> println("A is 20") } }
16. kotlin when not null and is null
You can evaluate a variable for null or not null in the branch condition by ignoring the when argument.
In the below code, we are evaluating the variable a
for null
and b
for not null
. The first condition evaluates to true so the remaining conditions will not be evaluated in the when statement.
fun main() { val a = null val b = "ABC" when { a == null -> println("A is null") b != null -> println("B is not null") else -> println("No") } }
17. Conclusion
In this article, we have seen Kotlin when as an expression and also statement along with various examples.
Pingback: kotlin foreach with index example: indices and withIndex - TedBlob
Pingback: "Kotlin quand avec plusieurs conditions" Code "Code Réponse de la réponse - Coder les réponses