When Block in Kotlin With Example

In this article, you will lean how to use when block in kotlin. Also, there are various examples that demonstrates the use of when block in kotlin. At last, you will go through different questions based on when block in kotlin.

Below are brief introduction to the topics we are going to cover in this post.

a. Introduction of when block in kotlin
b. How Does When Block in Kotlin Work?
c. Use When block in kotlin as a Statement
d. Use When block in kotlin as an Expression
e. Example to show Different Ways to Use When Block in kotlin
f. Questions on When block in Kotlin

How Does When Block in Kotlin Work?

When block in kotlin is same as switch case block in java or other programming languages.

When block in kotlin contains different cases block. when the program is run, each case is tested one by one from top to bottom. If any matching case is found, the code inside that case block is executed. After that, the code next to when block is executed. Unlike switch case block in java or other programming languages, we do not need break statement in the end of each case block. For example,

fun main(args: Array<String>) {
	val a = 10
	when(a) {
	    1 -> println("a is 1");
	    2 -> println("a is 2");
	    3 -> println("a is 3");
	    4 -> println("a is 4");
	    else -> println("a is neither 1 nor 2 nor 3 nor 4")       // Note that this else statement is optional
	}
}

Output:
a is neither 1 nor 2 nor 3 nor 4

Here, each case is checked one by one from top to bottom. when the condition matches, code inside that block is executed. since a is equal to 10, neither 1 nor 2 nor 3 nor 4 case matches, so, else statement is executed. Thus, output is a is neither 1 nor 2 nor 3 nor 4

You can use when block in kotlin in following ways
a. As a Statement
b. As an Expression

Now, we will see how to use when block as an expression or as a statement.

Use When Block in Kotlin As A Statement

When we use when block in kotlin as a statement, you do not necessarily have to use else block inside when block. For Example,

fun main(args: Array<String>) {
	val a = 10
	when(a) {
	    1 -> println("a is 1");
	    2 -> println("a is 2");
	    3 -> println("a is 3");
	    4 -> println("a is 4");
	}
}

Output:
Nothing will be printed.

a is 10. So, none of the case matches with a. since there is no else statement, nothing will be printed on the console.

Let’s go through another example of when block in kotlin

fun main(args: Array<String>) {
	val a = 24
	when(a) {
	    1 -> println("a is 1");
	    2 -> println("a is 2");
	    else -> println("a is neither 1 nor 2 ")       // Note that this else statement is optional
	}
}

Output:
a is neither 1 nor 2

a is 24. so, none of the case matches. thus, else block will be executed.

Use When block in Kotlin as an Expression

When we use when block in kotlin as an expression, you must use else block inside when block. For Example,

fun main(args: Array<String>) {
	val a = 10;
	val result = when(a) {
	    1 -> "a is 1";
	    2 -> "a is 2";
	    3 -> "a is 3";
	    4 -> "a is 4";
	    else -> "a is neither 1 nor 2 nor 3 nor 4" 
	}
	println(result)
}

Output:
a is neither 1 nor 2 nor 3 nor 4

Let’s see another example,

fun main(args: Array<String>) {
	val a = 10;
	val result = when(a) {
	    1 -> "a is 1";
	    2 -> "a is 2";
	    3 -> "a is 3";
	    4 -> "a is 4";
	}
	println(result)
}

When you run the program, you will get error –
‘when’ expression must be exhaustive, add necessary ‘else’ branch

This is because there is no else branch, but, when block has been used as an expression.




Example to show Different Ways to Use When Block in kotlin

There are many more ways to use when block. we will go through it one by one.

1. Combine two or more branches in same branch

You can combine two or more branches in single branch as shown below.

fun main(args: Array<String>) {
	val n = 10
	when (n) {
	    1, 2, 3 -> println("n is either 1 or 2 or 3")
	    4 -> println("n is 4")
	    else -> println("n is neither 1 nor 2 nor 3 nor 4")
	}
}

Output:
n is neither 1 nor 2 nor 3 nor 4

2. Check value in the range using when block

You can check the range of the argument as well in when block. You can do it as below.

fun main(args: Array<String>) {
	val n = 40
	when (n) {
	    in 1..10 -> println("n is between 1 and 10")
	    in 11..20 -> println("n is between 11 and 20")
	    in 21..30 -> println("n is between 21 and 30")
	    in 31..40 -> println("n is between 31 and 40")
	    in 41..50 -> println("n is between 41 and 50")
	    else -> println("n is greater than 50")
	}
}

Output:
n is between 31 and 40

3. Use expressions as branch condition in when block

You can use expression as branch condition in when block. All the branch conditions must be unique for a given argument in when block. You can use it as shown below.

fun main(args: Array<String>) {
	val a = 60
	val b = 70

	val canCheck = "true"
	when (canCheck) {
	    (a < b).toString() -> println("a is less than b")
	    else -> println("a is greater than or equal to b")
	}
}

Output:
a is less than b

4. Use when block in kotlin without passing any argument

You can use when block without passing any arguments in it. This is like if else block. You can use it as shown below.

fun main(args: Array<String>) {
	val x = 11
	when {
	    x % 2 != 0 -> print("x is odd")
	    else -> print("x is even")
	}
}

Output:
x is odd

5. Throw Exception in while block in kotlin

In kotlin, you can throw exception, in when block, after condition check as shown in the below example.

fun main(args: Array<String>) {
	val x = 12
	val y = 0
	when {
	    y == 0 -> throw NumberFormatException("Number can not be divided by 0")
	    else -> {
	        val z = x / y
	        print("x / y = $z")
	    }
	}
}

Error:
Exception in thread “main” java.lang.NumberFormatException: Number can not be divided by 0

6. isCase and smart cast in when block in kotlin

You can use is operator in when block to check if the argument is an instance of specified type or not. is operator in kotlin is similar to instanceof operator in java.

Since is operator is already checking the type of the argument, we do not need to explicitly cast the argument to the type. Compiler casts the arguments to its type automatically. This is called smart cast in kotlin.

One important features of smart cast –
We can use the methods and properties defined for given type directly in the case block.

fun main(args: Array<String>) {
	val sentence = "Tutorialwing is a platform where you can get free study materials."
	val prefix = "Tutorialwing"
	if (hasPrefix(sentence, prefix))
	    println("Sentence starts with prefix $prefix")
	else {
	    println("Sentence does not starts with prefix $prefix")
	}
}

fun hasPrefix(sentence: Any, prefix: String) = when(sentence) {
    is String -> sentence.startsWith(prefix)
    else -> false
}

Output:
Sentence starts with prefix Tutorialwing

Questions on When block in Kotlin

1. Guess the output of below program

fun main(args: Array<String>) {
	val sentence = "Tutoriawing is a platform where you can get free study materials."
	val prefix = "Tutorialwing"
	if (hasPrefix(sentence, prefix))
	    println("Sentence starts with prefix Tutorialwing")
	else {
	    println("Sentence does not starts with prefix Tutorialwing")
	}
}

fun hasPrefix(sentence: Any, prefix: String) = when(sentence) {
    is String -> sentence.startsWith(prefix)
    else -> false
}

2. Guess the output of the program

fun main(args: Array<String>) {
	val x = 11
	when {
	    x % 5 == 0 -> print("x is divisible by 5")
	    else -> print("x is not divisible by 5")
	}
}

3. Guess the output of the program

fun main(args: Array<String>) {
	val number = 80
	val n = "80"
	val result = when(n) {
	    "10"  -> print("Number is 10")
	    "20"  -> print("Number is 20")
	    "-50"  -> print("Number is -50")
	    number.toString()  -> print("Number is $number")
	    else -> print("Some other text")
	}
}

4. Guess the output of the program

fun main(args: Array<String>) {
	val number = 800
	val n = "80"
	val result = when(n) {
	    "10"  -> print("Number is 10")
	    "20"  -> print("Number is 20")
	    "-50"  -> print("Number is -50")
	    number.toString()  -> print("Number is $number")
	    else -> print("Some other text")
	}
}



5. Guess the output of the program

fun main(args: Array<String>) {
	val number = 89
	val result = when(number) {
	    in  0..10 -> println("Number is between 0 and 10")
	    in 10..50  -> print("Number is between 10 and 50")
	    in 51..100  -> print("Number is between 51 and 100")
	    else -> print("Number is either less than 0 or greater than 100")
	}
}

Conclusion

In this post, we have seen how to use when block in Kotlin. We have seen how to use when block in kotlin as expression or statement. We have also seen different ways to use when block – to throw exception, to check value in the range, to check data types etc.

Leave a Reply