Kotlin Tutoial
Basics
Control Flow
Array & String
Functions
Collections
OOPs Concept
Exception Handling
Null Safety
Regex & Ranges
Java Interoperability
Miscellaneous
Android
In Kotlin, the when
expression is a replacement for the traditional switch
statement known from other programming languages. However, when
is more powerful and flexible. It allows you to create branching logic based on the value of an expression. This tutorial will give you an understanding of how to use the when
expression in Kotlin.
The basic syntax of a when
expression looks like this:
when (expression) { value1 -> result1 value2 -> result2 ... else -> defaultResult }
Basic when
Expression
Given an integer, we can classify it:
val x = 5 when (x) { 1 -> println("x is 1") 2 -> println("x is 2") else -> println("x is neither 1 nor 2") }
This will output: "x is neither 1 nor 2"
Multiple Branch Conditions
You can combine multiple conditions in a single branch:
when (x) { 0, 1 -> println("x is 0 or 1") else -> println("x is not 0 or 1") }
Using Ranges
Check if a value belongs to a range:
when (x) { in 1..10 -> println("x is in the range") !in 10..20 -> println("x is outside the range") else -> println("none of the above") }
Using Expressions
Branch conditions can be more complex expressions:
val s = "Hello" when (s.length) { 0 -> println("Empty string") in 1..5 -> println("Short string") else -> println("Long string") }
Using when
Without an Argument
This is useful for replacing complex if-else-if
chains:
when { x < 5 -> println("x is less than 5") x % 2 == 0 -> println("x is even") else -> println("x is odd and >= 5") }
Returning Values
when
can be used as an expression that returns a value:
val description = when (x) { 1 -> "One" 2 -> "Two" else -> "Unknown" } println(description)
Checking Variable Types
You can use is
to check the type of a variable:
val obj: Any = "String" when (obj) { is String -> println("It's a string of length ${obj.length}") is Int -> println("It's an integer with value $obj") else -> println("Unknown type") }
The when
expression in Kotlin is a powerful construct that brings a lot of flexibility and clarity to conditional checks. By understanding its features and capabilities, you can simplify code logic and make it more readable.
when
with multiple conditions in Kotlin:The when
expression in Kotlin is similar to a switch statement in other languages and can be used with multiple conditions.
fun main() { val x = 5 val y = 10 when { x > y -> println("x is greater than y") x < y -> println("x is less than y") else -> println("x is equal to y") } }
when
in Kotlin:You can use the when
expression to match specific values.
fun main() { val day = "Monday" when (day) { "Monday" -> println("Start of the week") "Friday" -> println("End of the week") else -> println("Some other day") } }
when
expression in Kotlin:when
can also handle ranges and patterns.
fun main() { val score = 85 when (score) { in 90..100 -> println("Excellent") in 70 until 90 -> println("Good") else -> println("Needs improvement") } }
When
expression with smart casting in Kotlin:Smart casting allows the compiler to automatically cast a variable based on conditions.
fun printLength(value: Any) { when (value) { is String -> println("Length of string: ${value.length}") is List<*> -> println("Size of list: ${value.size}") else -> println("Unknown type") } } fun main() { printLength("Hello") printLength(listOf(1, 2, 3)) }
when
for exhaustive checking in Kotlin:when
can be used for exhaustive checking, ensuring all possible cases are covered.
fun describe(obj: Any): String { return when (obj) { is String -> "String" is Int -> "Int" is Double -> "Double" else -> "Unknown type" } }
when
expression:You can combine conditions using commas.
fun main() { val number = 7 when (number) { 1, 3, 5 -> println("Odd number") 2, 4, 6 -> println("Even number") else -> println("Some other number") } }
When
expression vs if-else
in Kotlin:when
expressions are often a more concise and readable alternative to multiple if-else
statements.
fun main() { val number = 42 val result = when { number < 0 -> "Negative" number > 0 -> "Positive" else -> "Zero" } println(result) }
When
expression with enums in Kotlin:when
can be used effectively with enums.
enum class Color { RED, GREEN, BLUE } fun getColorDescription(color: Color): String { return when (color) { Color.RED -> "Warm color" Color.GREEN -> "Cool color" Color.BLUE -> "Calm color" } }
When
expression and sealed classes in Kotlin:when
works well with sealed classes for exhaustive checking.
sealed class Result class Success(val message: String) : Result() class Error(val error: String) : Result() fun handleResult(result: Result): String { return when (result) { is Success -> "Success: ${result.message}" is Error -> "Error: ${result.error}" } }
when
expressions in Kotlin:You can nest when
expressions for more complex scenarios.
fun main() { val x = 5 val y = 10 when { x > 0 -> when { y > 0 -> println("Both x and y are positive") else -> println("Only x is positive") } else -> println("Neither x nor y is positive") } }
When
expression with function calls in Kotlin:You can use function calls in when
expressions for dynamic conditions.
fun isPositive(number: Int): Boolean = number > 0 fun main() { val x = 5 when { isPositive(x) -> println("Positive") else -> println("Non-positive") } }