Review the documentation , When , replaces the switch operator of type C languages, in this case Kotlin . Example:
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // Note the block
print("x no es 1 o 2")
}
}
If many cases should be handled in the same way, the conditions can be combined with a comma:
when (x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("de otra forma.")
}
We can use arbitrary expressions (not just constants) as branch conditions
when (x) {
parseInt(s) -> print("s codifica x")
else -> print("s no codifica a x")
}
We can also verify a value that can be in or ! in within a range or collection:
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
Having defined the above, the version of your code in Kotlin would be :
var variable = 2
when (variable) {
1 -> {
//Agrega aquí lo que realizaría si variable es igual 1
}
2, 3 -> {
//Agrega aquí lo que realizaría si variable es igual a 2 o 3
}
4 -> {
//Agrega aquí lo que realizaría si variable es igual 4
}
else -> { // Opción default
}
}