if (condition) {
// code block
}
else if (condtion) {
// code block
}
else {
// code block
}Braces are required for multi-line blocks. Use else if for multiple branches.
In Kotlin, if can return a value:
Use in or !in to check if a value is within a range:
val age = 25
if (age in 18..65) {
println("Eligible for work")
}
if (age !in 1..17) {
println("Eligible")
}In Kotlin, the when expression is used as a replacement for the traditional switch statement found in many other languages like Java, C, or C++. It's more flexible and powerful, and can be used both as a statement and as an expression.
Key Features of when:
break; it automatically exits after a matching branchBasic Example:
val day = 3
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
else -> println("Another day")
}Comparison: when vs switch
break statement to prevent fall-through.Example using ranges:
val score = 87
val grade = when (score) {
in 90..100 -> "A"
in 80..89 -> "B"
in 70..79 -> "C"
else -> "F"
}
println("Grade: $grade")when can also return a value:
val message = when (score) {
in 90..100 -> "Excellent"
in 80..89 -> "Good"
in 50..79 -> "Average"
else -> "Needs improvement"
}
println(message)whenKotlin’s when expression not only matches values, but also supports type checking using the is keyword. When you check an object's type with is inside a when block, Kotlin automatically smart casts the object to that type within that branch — no manual casting is needed.
This is especially useful when handling variables of type Any (the supertype of all types in Kotlin), or when processing objects whose type isn't known at compile time.
Example:
Explanation:
is String checks if obj is a String and safely allows access to length without casting.is List<*> checks for a list of any type — the wildcard * means the element type isn't specified.is Int matches integer values.else branch is used as a fallback for unmatched types.This approach is cleaner and safer than using manual casting like if (obj is String) println((obj as String).length), because Kotlin’s smart cast ensures type safety within the branch.
Ask the AI if you need help understanding or want to dive deeper in any topic