How to Use when with is Keyword in Kotlin
In Kotlin, you can use the
when expression with the is keyword to check the type of a variable and execute code based on that type. This allows you to write clear and concise type checks without explicit casting.Syntax
The when expression evaluates a variable against multiple conditions. Using is inside when checks if the variable is of a certain type.
when (variable) {- starts the expression with the variable to checkis Type ->- checks if variable is ofTypeelse ->- default case if no type matches
kotlin
when (variable) {
is Type1 -> {
// code for Type1
}
is Type2 -> {
// code for Type2
}
else -> {
// code if no type matches
}
}Example
This example shows how to use when with is to check the type of an Any variable and print a message accordingly.
kotlin
fun describe(obj: Any): String {
return when (obj) {
is Int -> "Integer: $obj"
is String -> "String of length ${obj.length}"
is Boolean -> "Boolean value: $obj"
else -> "Unknown type"
}
}
fun main() {
println(describe(42))
println(describe("hello"))
println(describe(true))
println(describe(3.14))
}Output
Integer: 42
String of length 5
Boolean value: true
Unknown type
Common Pitfalls
One common mistake is forgetting that is checks the type but does not cast automatically outside the when branch. Inside each branch, Kotlin smart casts the variable to the checked type.
Another pitfall is not including an else branch, which can cause the when expression to be non-exhaustive if the compiler cannot verify all types are covered.
kotlin
fun checkType(obj: Any) {
when (obj) {
is String -> println(obj.length) // smart cast works here
// Missing else branch can cause warning if not all types covered
}
}
// Wrong: Trying to use obj as String outside when branch
fun wrongCast(obj: Any) {
if (obj is String) {
println(obj.length) // OK
}
// println(obj.length) // Error: obj is Any here
}Quick Reference
Tips for using when with is keyword:
- Use
is Typeto check variable type insidewhen. - Kotlin smart casts variable to the checked type inside the branch.
- Always provide an
elsebranch for completeness. - Use
!is Typeto check if variable is NOT of a type.
Key Takeaways
Use
when with is to check variable types cleanly in Kotlin.Inside each
is Type branch, Kotlin smart casts the variable to that type automatically.Always include an
else branch to handle unexpected types.Remember
is checks type but does not cast outside the when branch.You can also use
!is to check if a variable is not of a certain type.