When given an argument, the when
-statement matches the argument against the branches in sequence. The matching is done using the ==
operator which performs null checks and compares the operands using the equals
function. The first matching one will be executed.
when (x) {
"English" -> print("How are you?")
"German" -> print("Wie geht es dir?")
else -> print("I don't know that language yet :(")
}
The when statement also knows some more advanced matching options:
val names = listOf("John", "Sarah", "Tim", "Maggie")
when (x) {
in names -> print("I know that name!")
!in 1..10 -> print("Argument was not in the range from 1 to 10")
is String -> print(x.length) // Due to smart casting, you can use String-functions here
}