The "when" expression in Kotlin is used as a replacement for the switch statement in other programming languages. It allows you to define multiple branches of code and execute the branch that matches a given condition.
Here is the syntax of the "when" expression:
1 2 3 4 5 6 7 8 9 10 11 |
when (variable) { value1 -> { // Code to execute when variable equals value1 } value2 -> { // Code to execute when variable equals value2 } else -> { // Code to execute when none of the above conditions are met } } |
The "variable" in the when expression is the value that you want to match against. You can provide multiple values separated by commas if you want to execute the same code for different values.
Each branch is introduced with the value followed by an arrow (->). Inside the branch, you write the code that should be executed when the corresponding condition is met.
If none of the conditions match the given variable, the "else" branch (optional) is executed. It acts as a default branch that covers any other possible values.
The "when" expression can also be used without an argument. In this case, you provide conditions directly inside the branches. For example:
1 2 3 4 5 6 7 8 9 10 11 |
when { condition1 -> { // Code to execute when condition1 is true } condition2 -> { // Code to execute when condition2 is true } else -> { // Code to execute when none of the above conditions are true } } |
Using the "when" expression, you can simplify complex if-else chains and make your code more concise and readable.
How to use 'when' with type-checking in Kotlin?
In Kotlin, you can use the when
expression with type-checking to check the type of an object and perform specific actions based on the type.
The syntax for using when
with type-checking is as follows:
1 2 3 4 5 6 7 8 9 10 11 |
when (objectToCheck) { is TypeOne -> { // Action to perform if objectToCheck is of TypeOne } is TypeTwo -> { // Action to perform if objectToCheck is of TypeTwo } else -> { // Action to perform if objectToCheck does not match any types } } |
Here's an example to illustrate how to use when
with type-checking:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
fun processData(data: Any) { when (data) { is String -> { println("String: $data") } is Int -> { println("Integer: $data") } is Boolean -> { println("Boolean: $data") } else -> { println("Unknown type: $data") } } } fun main() { processData("Hello") // Output: String: Hello processData(42) // Output: Integer: 42 processData(true) // Output: Boolean: true processData(3.14) // Output: Unknown type: 3.14 } |
In this example, when the processData
function is called with different types of data, the when
expression checks the type of the data
parameter and executes the corresponding block of code based on the type.
Note that the else
branch is optional, and it will be executed if none of the other branches match.
How to use the 'when' expression in Kotlin?
The when
expression in Kotlin is a more powerful alternative to the traditional switch
statement in other programming languages. It allows you to branch your code based on multiple conditions.
Here's how you can use the when
expression in Kotlin:
- Basic usage:
1 2 3 4 5 6 7 8 9 |
val x = 5 when (x) { 1 -> println("x is 1") 2 -> println("x is 2") 3, 4 -> println("x is either 3 or 4") in 5..10 -> println("x is between 5 and 10 (inclusive)") else -> println("x is unknown") } |
In this example, the when
expression checks the value of x
and executes the branch whose condition matches.
- Checking type:
1 2 3 4 5 6 7 |
val obj: Any = "Hello" when (obj) { is String -> println("obj is a String") is Int -> println("obj is an Int") else -> println("obj is something else") } |
The when
expression can also check the type of an object.
- Using when as an expression:
1 2 3 4 5 6 7 |
val result = when (x) { 1 -> "x is 1" 2 -> "x is 2" else -> "x is unknown" } println(result) |
You can assign the result of the when
expression to a variable, which allows you to use it in further calculations or print it.
These are just a few examples of how to use the when
expression in Kotlin. It provides many more possibilities, such as using ranges, combining conditions, and more.
How to use 'when' with sealed classes in Kotlin?
In Kotlin, sealed classes are used to represent restricted class hierarchies, where all subclasses must be defined within the same file. The when
expression is often used with sealed classes to handle different cases based on the type of the sealed class instance.
Here's an example of how to use when
with sealed classes in Kotlin:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
sealed class Result data class Success(val value: Int) : Result() data class Error(val message: String) : Result() object Loading : Result() fun processResult(result: Result) { when (result) { is Success -> { println("Success: ${result.value}") } is Error -> { println("Error: ${result.message}") } Loading -> { println("Loading...") } } } fun main() { val result1 = Success(10) processResult(result1) val result2 = Error("Something went wrong") processResult(result2) processResult(Loading) } |
In this example, the sealed class Result
has three subclasses: Success
, Error
, and Loading
. The when
expression in the processResult
function is used to handle different cases based on the type of result
.
When result
is of type Success
, it prints the value of the success. When result
is of type Error
, it prints the error message. And when result
is of type Loading
, it prints "Loading...".
In the main
function, we create different instances of the Result
subclasses and pass them to the processResult
function to see how they are handled by the when
expression.
By using when
with sealed classes, you can easily handle different cases based on the type of the sealed class instance, ensuring that all possible cases are covered.
What is the return type of a 'when' expression in Kotlin when used as an expression?
The return type of a when
expression in Kotlin, when used as an expression, is the common supertype of all its branch conditions.
If the branch conditions have no common supertype, the return type of the when
expression will be Any?
, which is the top-level supertype in Kotlin.
However, if the branch conditions have a common supertype, that will be the return type of the when
expression.