Kotlin control flow resembles Java but many constructs are expressions that return values—if and when can assign directly to variables.
if and when
val max = if (a > b) a else b
when (grade) {
"A" -> println("Excellent")
"B", "C" -> println("Pass")
else -> println("Review")
}
Loops
for (item in collection), while, and do-while match familiar patterns. Ranges: 1..10, until, step.
Important interview questions and answers
- Q: when vs switch?
A:whenis expression-based, supports ranges, types, and no fall-through bugs like C-style switch. - Q: Is if an expression?
A: Yes—branches must be expressions or blocks with a single value when used in assignment.
Self-check
- How do you write an inclusive range 1 through 5?
- Can
whenreplace an if-else chain?
Tip: when replaces switch without fall-through bugs—like modern C# switch expressions.
Interview prep
- when vs switch?
when is expression-based without fall-through.
- if expression?
Branches can return values for assignment.