Reading — step 1 of 5
Learn
~1 min readControl Flow
In Kotlin, if is an expression — it returns a value:
val label = if (n > 0) "positive" else if (n < 0) "negative" else "zero"
No ternary operator — if/else does the job.
when is Kotlin's pattern-match-y switch. Much more flexible than Java's switch:
val grade = when {
score >= 90 -> "A"
score >= 80 -> "B"
score >= 70 -> "C"
else -> "F"
}
val kind = when (x) {
0, 1 -> "low"
in 2..10 -> "medium" // range
is String -> "a string" // type check
else -> "other"
}
when can match values, ranges, types, or arbitrary boolean conditions. Like if, it's an expression.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…