Smart casts let Kotlin automatically convert a variable to a specific type after you check it. This makes your code simpler and safer.
0
0
Smart casts in when and if in Kotlin
Introduction
When you want to check a variable's type and then use it as that type without extra code.
When you use an if statement to check if a variable is a certain type and want to access its properties directly.
When you use a when expression to handle different types of a variable cleanly.
When you want to avoid writing manual casts and keep your code easy to read.
Syntax
Kotlin
if (variable is Type) { // variable is smart cast to Type here } when (variable) { is Type1 -> { // variable is smart cast to Type1 here } is Type2 -> { // variable is smart cast to Type2 here } else -> { // variable is not any of the above types } }
Kotlin automatically casts the variable inside the if or when block after checking its type.
You don't need to use explicit casts like variable as Type inside these blocks.
Examples
Here,
obj is checked if it is a String. Inside the if block, Kotlin lets you use obj as a String directly.Kotlin
val obj: Any = "Hello" if (obj is String) { println(obj.length) // smart cast to String }
The when expression checks the type of
obj. Each branch smart casts obj to the checked type.Kotlin
val obj: Any = 123 when (obj) { is Int -> println(obj + 1) // smart cast to Int is String -> println(obj.length) else -> println("Unknown type") }
Sample Program
This program uses a when expression with smart casts to handle different types of obj. It prints a description based on the type.
Kotlin
fun describe(obj: Any): String { return when (obj) { is Int -> "Integer: ${obj + 1}" is String -> "String of length ${obj.length}" else -> "Unknown type" } } fun main() { println(describe(10)) println(describe("Kotlin")) println(describe(3.14)) }
OutputSuccess
Important Notes
Smart casts only work if the variable cannot change between the check and usage (like val or local variables).
If the variable is mutable or a property with a custom getter, Kotlin may not smart cast it.
Summary
Smart casts let you use variables as a specific type after checking their type.
They work automatically inside if and when blocks.
This feature makes your Kotlin code cleaner and safer.