1. What is when Expression in Kotlin?
When it comes to decision-making and an enhanced approach to branching, the when construct in Kotlin language plays a pivot role. This comprehensive tutorial will surely provide you with the intricacies of the when expression in Kotlin along with its capabilities with a bunch of examples. We will also go through some benefits of using the Kotlin when conditional construct, its various working principles, and some core reasons behind its use.
1.1. Kotlin when Syntax Overview
Let's look at the basic syntax of the when expression in Kotlin. The box below showcases the syntax of the Kotlin when construct.
when (expression) { value1 -> ( code to execute against value1 ) value2 -> ( code to execute against value2 ) else -> ( code to execute when nothing matches ) }
1.2. when Syntax Explained
The syntax of Kotlin when statement has folllowing pricks.
- We use the when keyword to use this conditional construct.
- The when keyword is followed by round() brackets containing the expression to evaluate.
- After the expression, the curly{} brackets holds the logic or code to execute based on the expression evaluated.
2. Working Principles of Kotlin when Construct
Basically, when is one of the Kotlin keywords, we can utilize it as an expression or without expression in our code. There are other use cases and principles of utilizing the when, which are described below with instances.
3.1. Kotlin when as an Expression
The following example illustrates the use of when as an expression.
Example
fun main(){ val num = 3 val selectedNum = when(num) { 1 -> "One" 2 -> "Two" 3 -> "Three" 4 -> "Four" 5 -> "Five" else -> "invalid number" } println("Your chosen number is $selectedNum.") }
3.2. Kotlin when Without Expression
This is not compulsory to use the when as an expression, and we can simply incorporate this construct without an expression. The below instance clarifies this statement.
Example
fun main(){ val num = 6 val selectedNum = when(num) { 1 -> println("One") 2 -> println("Two") 3 -> println("Three") 4 -> println("Four") 5 -> println("Five") else -> println("Invalid Number") } }
Note:
3.3. Multiple Statements of when Using Braces{}
We can also utilize this construct to parse multiple statements via curly braces{}. See the following example to understand this case.
Example
fun main(){ val num = 2 val selectedNum = when(num) { 1 -> { println("One") println("Sunday") } 2 -> { println("Two") println("Wednesday") } 3 -> { println("Three") println("Friday") } else -> "Invalid Selection" } }
Two Wednesday
3.4. Handling Multiple Conditions Using when
We can also run the same logic for multiple choices and for that purpose, we use commas(,) to separate multiple branches of the condition.
Example
fun main(args: Array){ var number = 12 when(number) { 1, 2, 3, 4, 5 -> println("You are in Kindle Section.") 6, 7, 8, 9, 10 -> println("You are in High Section.") 11, 12 -> println("You are in College Section.") 13, 14, 15, 16 -> println("You are in University Section.") else -> println("invalid input") } }
3.5. Evaluating Ranges Using when
We can also check the ranges of input provided in the when condition. We can create a range using a double dot(..) operator, which checks if a number falls within a range. See the below example to comprehend this case.
Example
fun main(){ val score = 75 val grade = when (score) { in 0..40 -> "Fail" in 41..70 -> "Pass" in 71..100 -> "Excellent" else -> "Invalid score" } println(grade) }
3.6. Enum Smart Matching Using when
The enum smart matching in Kotlin using the when construct elevates your code from basic value checks to powerful pattern recognition. The compiler automatically deconstructs the structure of the enum. It analyzes it for target-specific variants, ranges, or combinations through concise clauses, which resultantly cleans the code and handles the code logic elegantly. Check the following instance to comprehend the enum smart matching in Kotlin programming.
Example
enum class Color { RED, GREEN, BLUE } fun main(){ val selectedColor: Color = Color.BLUE val message = when (selectedColor) { Color.RED -> "Selected color is Red" Color.GREEN -> "Selected color is Green" Color.BLUE -> "Selected color is Blue" } println(message) }
3.7. Null Checks Using when
The when expression also makes it easy to check for null values in Kotlin code and offers several ways to handle the null values.
Example
fun main(){ val value: String? = null val result = when (value) { null -> "Value is null. else -> "Value is $value. } println(result) }
3.8. Using when For Smart Casting
In Kotlin, the smart casting allow automatic casting of data types based on certain conditions. We use the is expression to get a smart cast for free, so we can use the data without any further check. Check the below example to comprehend this technique of when construct.
Example
fun describeValue(value: Any) { when (value) { is String -> println("It's a String with length ${value.length}") is Int -> println("It's an Int with value $value") is Double -> println("It's a Double with value $value") else -> println("Unknown type") } /*At this point, within each branch of the 'when' expression, the 'value' is smart-cast to the specific type.*/ } fun main() { describeValue("Hello, Kotlin!") describeValue(42) describeValue(3.14) describeValue(true) }
It's a String with length 14 It's an Int with value 42 It's a Double with value 3.14 Unknown type
3.9. Using when Without Expression
Sometimes, we can use the when expression in Kotlin language without any explicit argument. In that case, the when expression simply turns into an if-else chain where case braches evaluate the conditions directly. See the below example.
Example
fun main(){ val x = 3 val y = 3 when { /* No Argument for when */ x > y -> println("x is greater than y!") x == y -> println("x and y are equal!") else -> println("y is greater than x!") } }
Note:
3. Why Use when in Kotlin?
Although there are certain advantages of using the when conditional construct, which makes it really handy for Java users. Previously, we were using switch statements in Java, C++, PHP, and other programming languages. But in Kotlin, the when statement revolutionized the coding and made decision-making much easier.
Below are some features/advantages, that tell us why to use when construct in Kotlin programming.
- The edge of when over Kotlin if..else is that it eliminates the nesting making your code clean and compact.
- We can use when as a statement or as an expression.
- It has a safe and better design, making it helpful.
- The clear and intuitive syntax of Kotlin when construct, makes it easier to follow the code logic and understand.
- The expressiveness of when supports rich comparisons, allowing you to match against ranges, patterns, and even combinations of conditions.
- It also acts as a branching and expression tool as it can return values and can even be used with any expression.
- We can also use when without any argument, unlike the switch statement.
- All these features make the when construct a powerful tool for programmers instead of the old switch-case construct.