when
operator is a replacement of switch
operator in other languages.
when
operator matches its argument with all the branches until it matches with anyone, else it executes the else
block.
var intNumber = 10
when (intNumber) {
1 -> print("value is 1")
2 -> print("value is 2")
else -> {
print("value of intNumber is neither 1 nor 2")
}
}
It can be used as an expression where the value of the satisfied branch becomes the value of the overall expression.
fun calculateAreaOfCircle(radius: Float): Float {
return (22 * radius * radius) / 7
}
fun calculateAreaOfSquare(sideLength: Float): Float {
return (sideLength * sideLength)
}
fun calculateArea(shape: Shape) : Float {
var area = when (shape) {
is Circle -> calculateAreaOfCircle( radius = 6f)
is Square -> calculateAreaOfSquare(sideLength = 10f)
else -> {
print("invalid shape")
return 0f
}
}
//use area for further use
return area
}
In the above example, based on the shape type, the overall expression is replaced with the satisfied branch.
Or it can be used as a statement where the satisfied block’s statements will be performed.
var count = 100
when (count) {
in 0 until 100 -> {
//count is between 1 to 99
count++
}
else -> {
//count is greater than 99
//set it to 0
count = 0
}
}
The else
branch is evaluated if none of the other branch conditions is satisfied. If when
is used as an expression, the else
branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions.
val boolValue : Boolean = false
when (boolValue) {
false -> {
print("value is false")
}
true -> {
print("value is true")
}
}
The branch conditions may be combined with a comma (,
)
val value = 100
when (value) {
0, 1 -> print("x == 0 or x == 1")
!in 10..20, !in 30..40 -> {
print("not in 10 to 20 and 30 to 40")
}
else -> print("otherwise")
}
We can also check a value for being in
or !in
a range or a collection.
val value = 21
val initialPrimeNumbers = intArrayOf(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47)
when (value) {
in 10..20 -> print("in 10 to 20")
!in 30 until 40 -> print("not in 30 to 39")
in initialPrimeNumbers -> print("exist in array")
else -> print("not present anywhere")
}
Another possibility is to check that a value is
or !is
of a particular type.
val shape : Shape = Circle()
when (shape) {
is Circle -> print("shape is a Circle class object")
is Square -> print("shape is a Square class object")
else -> {
print("invalid shape")
}
}
when
can also be used as a replacement for an if-else-if
chain. If no argument is supplied, the branch conditions are simply boolean expressions, and a branch is executed when its condition is true
val num = 10
when {
isPrime(num) -> print("num is a prime number")
isComposite(num) -> print("num is a composite number")
else -> {
print("num is neither prime nor composit")
}
}