0
0
Kotlinprogramming~10 mins

Smart casts in when and if in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Smart casts in when and if
Start
Check type with if/when
Smart cast variable
Use variable as casted type
End
The program checks a variable's type using if or when, then automatically treats it as that type inside the block.
Execution Sample
Kotlin
fun demo(x: Any) {
  if (x is String) {
    println(x.length)
  } else {
    println("Not a string")
  }
}
Checks if x is a String, then uses x as String inside if block without explicit cast.
Execution Table
StepConditionCondition ResultSmart Cast AppliedActionOutput
1x is StringTruex as StringPrint x.length5
2x is StringFalseNo castPrint "Not a string"Not a string
💡 Execution ends after printing output based on type check.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
xAny ("Hello")Smart cast to StringNo castAny/String depending on branch
Key Moments - 2 Insights
Why can we use x.length without casting inside the if block?
Because the condition 'x is String' is true at step 1, Kotlin smart casts x to String automatically inside that block, as shown in the execution_table.
What happens if the condition 'x is String' is false?
At step 2, the condition is false, so no smart cast happens and x remains Any, so we cannot use String properties safely.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the smart cast applied at step 1?
ANo cast
Bx as Int
Cx as String
Dx as Any
💡 Hint
Check the 'Smart Cast Applied' column at step 1 in the execution_table.
At which step does the program print "Not a string"?
AStep 2
BBoth steps
CStep 1
DNever
💡 Hint
Look at the 'Output' column in the execution_table for each step.
If x was an Int, what would happen to the smart cast in the if block?
Ax would be smart cast to String
BNo smart cast would happen
Cx would be smart cast to Int
DProgram would crash
💡 Hint
Refer to the 'Condition Result' column in the execution_table and how smart casts depend on it.
Concept Snapshot
Smart casts let Kotlin treat a variable as a specific type after checking with if or when.
Syntax: if (x is Type) { use x as Type }
No explicit cast needed inside the block.
If condition false, no cast happens.
Smart casts improve safety and readability.
Full Transcript
This example shows how Kotlin uses smart casts in if and when statements. When the program checks if variable x is a String, and the condition is true, Kotlin automatically treats x as a String inside the if block. This means you can use String properties like length without casting. If the condition is false, no smart cast happens, and x remains its original type. The execution table shows two steps: one where x is a String and smart cast applies, printing the length; and one where x is not a String, so it prints "Not a string". This helps beginners understand how Kotlin safely narrows types without extra code.