Mastering ‘When’ in Kotlin: Tips, Tricks, and Best Practices
When it comes to Kotlin, the keyword “when” is one of the most useful constructs in the language. It’s like a Swiss Army knife for developers, with a variety of different use cases and applications.
🔎 What is “when” in Kotlin?
In Kotlin, “when” is a control flow construct that works like a switch statement in other languages. It allows you to match a value against a series of possible options, and execute different code based on which option matches.
Here’s an example of how “when” can be used to evaluate a variable and perform different actions:
val x = 1
when (x) {
1 -> println("x is 1")
2 -> println("x is 2")
else -> println("x is neither 1 nor 2")
}
In this example, we use “when” to evaluate the value of the variable “x”. If “x” is 1, we print a message saying “x is 1”. If “x” is 2, we print a message saying “x is 2”. If “x” is neither 1 nor 2, we print a message saying “x is neither 1 nor 2”.
🤔 When to use “when” in Kotlin?
There are many situations where “when” can be useful in Kotlin. Here are a few examples:
✅ Matching against multiple values
One of the most common use cases for "when" is to match a value against multiple possible options. This is much more concise and readable than using a series of if/else statements.
when (x) {
1, 2 -> println("x is either 1 or 2")
in 3..10 -> println("x is between 3 and 10")
else -> println("x is something else")
}
In this example, we use “when” to match the value of “x” against multiple options. We can use commas to match against multiple values at once, or ranges to match against a range of values.
✅ Checking for type
Another common use case for "when" is to check the type of an object. This is similar to using "instanceof" in other languages.
val obj: Any = "Hello, world!"
when (obj) {
is String -> println("obj is a String with length ${obj.length}")
is Int -> println("obj is an Int with value $obj")
else -> println("obj is something else")
}
In this example, we use “when” to check the type of the “obj” variable. If “obj” is a String, we print a message with the length of the string. If “obj” is an Int, we print a message with the value of the integer. If “obj” is something else, we print a generic message.
✅ Using “when” as an expression
In Kotlin, "when" can also be used as an expression, which allows you to assign the result of the "when" block to a variable.
val result = when (x) {
1 -> "x is 1"
2 -> "x is 2"
else -> "x is neither 1 nor 2"
}
println(result)
In this example, we use “when” as an expression to assign the result of the block to the “result” variable. We can then print the value of “result” to the console.
😂 Conclusion
In conclusion, “when” is an incredibly useful construct in Kotlin that can save you a lot of time and effort when writing code. Whether you’re matching against multiple
Don’t forget to give it a clap and follow me. Have feedback or question let’s get connected by Clicking Here