Kotlin has no cond ? a : b operator. Use if as an expression: val max = if (a > b) a else b. For more than two outcomes use when, Kotlin's switch: when { x < 0 -> "neg"; else -> "pos" }. The ?: you do see in Kotlin is the Elvis operator, which only tests for null.
In Java, if is a statement and the ternary ?: is the way to pick a value. In Kotlin, if and when are expressions: they give a value you can assign, return or pass, so the language never needed a separate ternary. The sections below cover if as an expression, when in place of switch, when with comparisons and ranges, the compile error a missing branch gives you, guard conditions in when, and where the Elvis operator and takeIf fit, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1if as an expressionRecommended
Write the condition, the value for true and the value for false: if (a > b) a else b. It is the direct replacement for Java's a > b ? a : b, and it fits anywhere a value does: a val, a return value, a function argument or a string template. Each branch can also be a block in braces; the last expression in the block is its value. When if is used as a value, the else is required, because the expression must give something on both paths.
fun sign(n: Int): String = if (n < 0) "negative" else if (n == 0) "zero" else "positive" fun main() { val a = 3 val b = 5 // Java: int max = a > b ? a : b; val max = if (a > b) a else b println("max = $max") // Inline, inside a string template for (count in listOf(1, 3)) { println("$count ${if (count == 1) "file" else "files"} copied") } // A block's last expression is its value val score = 72 val result = if (score >= 50) { println("checking $score") "pass" } else { "fail" } println(result) // else if chains give a value too for (n in listOf(-4, 0, 9)) println("$n is ${sign(n)}") }
Output
max = 5 comes from the one-line if, and the template picks file or files the way a ternary would. The block form runs println first, then gives "pass", its last line. Drop the else from val max = if (a > b) a and the compiler stops with 'if' must have both main and 'else' branches when used as an expression. For this exact case, maxOf(a, b) also exists. Past two branches, a chain of else if works, but when (next sections) reads better.
2when instead of switch-case
Kotlin has no switch; when replaces it. Each branch is value -> result, several values share a branch with commas, and else plays the part of default. There is no fall-through, so there is no break: the first matching branch runs and when is done. A branch can match a range with in, and like if, the whole when gives a value.
fun dayType(day: String): String = when (day) { "Sat", "Sun" -> "weekend" "Mon", "Tue", "Wed", "Thu", "Fri" -> "weekday" else -> "not a day" } fun status(code: Int): String = when (code) { 200 -> "OK" in 300..399 -> "redirect" 404 -> "not found" in 400..499 -> "client error" in 500..599 -> "server error" else -> "unknown" } fun main() { for (day in listOf("Sat", "Wed", "Funday")) { println("$day: ${dayType(day)}") } for (code in listOf(200, 302, 404, 418, 503, 99)) { println("$code ${status(code)}") } // As a statement: no break, and no fall-through val command = "stop" when (command) { "start" -> println("starting") "stop" -> { println("stopping") println("saved") } else -> println("unknown command") } }
Output
Order matters: 404 hits its own branch, not found, because it comes before in 400..499, while 418 skips it, reaches the range and prints client error. The "stop" branch runs its two lines, stopping and saved, and nothing after it runs. Strings are compared with == (equals), so when on a String works with no extra setup.
3when with <, >= and ranges
A branch of when (x) can't start with a comparison: when (x) { < 0 -> … } stops here with Syntax error: Expecting an expression. Leave out the subject instead. A bare when { … } takes a full condition on each branch, so it replaces an if/else if ladder, and the branches can test different things. When you keep the subject, compare through ranges and collections with in and !in, and use when (val x = …) to name a computed subject.
fun feel(celsius: Int): String = when { celsius < 0 -> "freezing" celsius < 15 -> "cold" celsius <= 25 -> "mild" else -> "hot" } fun shipping(total: Double, member: Boolean): String = when { member -> "free (member)" total >= 50.0 -> "free (over 50)" else -> "4.99" } fun main() { for (t in listOf(-5, 12, 25, 31)) println("$t C: ${feel(t)}") // Branches can test different things println(shipping(20.0, member = true)) println(shipping(64.0, member = false)) println(shipping(20.0, member = false)) // With a subject, compare through in and ranges val vowels = setOf('a', 'e', 'i', 'o', 'u') for (c in "k2o!") { val kind = when (c) { in vowels -> "vowel" in 'a'..'z' -> "consonant" in '0'..'9' -> "digit" else -> "other" } println("$c: $kind") } // when (val x = ...) names the subject for the branches when (val len = "Kotlin".length) { in 0..<5 -> println("short: $len") else -> println("long: $len") } }
Output
The first true branch wins, so 12 stops at celsius < 15 and never reaches the <= 25 test, and 25 is mild because <= includes it. The member gets free (member) whatever the total. In the subject form, o matches in vowels before the wider in 'a'..'z'. 0..<5 is a range that leaves out 5 (the same as 0 until 5), and len exists only inside the when.
4Exhaustive when: the “must be exhaustive” error
A when that gives a value must cover every possible input. For an Int or a String that means an else. For an enum, a sealed class or a Boolean, listing every case is enough, and that is the better choice: with no else, adding a constant to the enum later makes the compiler point at every when that misses it. The program below never runs, because action forgets YELLOW.
enum class Light { RED, YELLOW, GREEN } fun action(light: Light): String = when (light) { Light.RED -> "stop" Light.GREEN -> "go" } fun main() { for (light in Light.entries) println("$light: ${action(light)}") }
Output
The compiler stops with 'when' expression must be exhaustive. Add the 'YELLOW' branch or an 'else' branch. Add Light.YELLOW -> "slow down" and run it again: the three lights print. Here the same error also stops a when used as a plain statement on an enum parameter, a sealed type or a Boolean, while a statement on an Int or String may skip cases. The next section shows the sealed-class version, which also needs no else.
5Guard conditions and sealed classes
is Card -> checks the type and smart-casts the subject, so the branch can read p.amount. Since Kotlin 2.2, a branch can add a guard: is Card if p.amount > 1000 -> matches only cards over 1000. A guarded branch doesn't count toward exhaustiveness, so the plain is Card -> still has to follow it. On older Kotlin, put an if inside the branch instead; both forms are below.
sealed interface Payment data class Card(val last4: String, val amount: Int) : Payment data class Cash(val amount: Int) : Payment data object Voucher : Payment // Kotlin 2.2 and later: a guard adds a condition to a branch fun review(p: Payment): String = when (p) { is Card if p.amount > 1000 -> "card ${p.last4}: needs approval" is Card -> "card ${p.last4}: ok" is Cash -> "cash ${p.amount}" Voucher -> "voucher" } // Older Kotlin: an if inside the branch fun reviewOld(p: Payment): String = when (p) { is Card -> if (p.amount > 1000) "card ${p.last4}: needs approval" else "card ${p.last4}: ok" is Cash -> "cash ${p.amount}" Voucher -> "voucher" } fun main() { val payments = listOf( Card("4242", 1500), Card("1881", 40), Cash(20), Voucher, ) for (p in payments) println(review(p)) // Both versions give the same answers println(payments.map(::review) == payments.map(::reviewOld)) }
Output
The 1500 card takes the guarded branch and prints card 4242: needs approval; the 40 card skips it and lands on card 1881: ok. Neither function has an else: the sealed interface has exactly three subtypes and both cover them. Delete the plain is Card -> line and the build fails with 'when' expression must be exhaustive. Add the 'is Card' branch or an 'else' branch. The last line, true, confirms the old and new forms agree.
6The Elvis operator and takeIf
a ?: b looks like half a ternary, but it is the Elvis operator: it gives a unless a is null, and then b. It tests for null and nothing else (see check for null for the full set of null operators). To use it with a real condition, turn the condition into a null first: x.takeIf { test } gives x when the test passes and null when it fails, so x.takeIf { … } ?: fallback reads as "x if it passes, otherwise fallback". takeUnless flips the test.
fun main() { // ?: picks the right side only when the left side is null val nickname: String? = null println("Hi, ${nickname ?: "guest"}") // An empty string is not null, so ?: keeps it val title: String? = "" println("[${title ?: "Untitled"}]") println("[${if (title.isNullOrEmpty()) "Untitled" else title}]") // takeIf keeps the value when the test passes, else gives null for (raw in listOf("8080", "99999", "abc")) { val port = raw.toIntOrNull()?.takeIf { it in 1..65535 } ?: 80 println("$raw -> $port") } // takeUnless is the opposite test val name = " " println(name.takeUnless { it.isBlank() } ?: "anonymous") }
Output
The null nickname becomes Hi, guest, but the empty title prints []: ?: saw a value, not a null. Asking the real question with if gives [Untitled]. 99999 parses but fails the range test, so takeIf turns it into null and the Elvis gives 80; abc is already null after toIntOrNull(). Use takeIf when the value itself is what you keep; for two unrelated values, if (cond) a else b is clearer.
7Which should you use?
| Method | Needs else | Best for |
|---|---|---|
| if (c) a else b | Yes, as a value | Two outcomes: the Java ternary |
| when (x) { v -> … } | Unless exhaustive | One value against constants, ranges or types: switch-case |
| when { x < 0 -> … } | Yes, as a value | Comparisons such as < and >=, else-if ladders |
| when over an enum or sealed type | No, list every case | Closed sets of cases the compiler checks for you |
| is T if cond -> | Guards don't count | A type plus an extra test (Kotlin 2.2+) |
| x.takeIf { … } ?: d | No | Keeping a value only when it passes a test |
| a ?: b | No | A default for null only; not a ternary |
Frequently asked questions
Does Kotlin have a ternary operator?
No. Kotlin has no cond ? a : b; writing val max = a > b ? a : b stops the build with Syntax error: Unexpected tokens (use ';' to separate expressions on the same line). Use if as an expression instead: val max = if (a > b) a else b. It does the same job and can be used anywhere a value fits.
Why doesn't Kotlin have a ternary operator?
Because if is already an expression that gives a value, so if (a > b) a else b covers everything a > b ? a : b does, and when covers the longer chains. The ? character also already has several jobs in Kotlin: nullable types (String?), safe calls (?.) and the Elvis operator (?:).
Is ?: the ternary operator in Kotlin?
No. a ?: b is the Elvis operator: it gives a when a is not null and b when it is. It never looks at a condition, so "" ?: "default" gives the empty string. For a condition, write if (cond) a else b, or combine takeIf with Elvis: x.takeIf { it > 0 } ?: 1.
How do I write a switch-case statement in Kotlin?
Use when (x) { 1 -> …; 2, 3 -> …; in 4..9 -> …; else -> … }. Commas join several values into one branch, in matches a range or collection, and else replaces default. There is no fall-through and no break: only the first matching branch runs. when also gives a value, so val name = when (x) { … } works.
How do I use when with greater than or less than?
Leave out the subject and write full conditions: when { x < 0 -> "negative"; x < 10 -> "small"; else -> "large" }. when (x) { < 0 -> … } does not compile. If you keep the subject, express the comparison as a range: in 0..9 -> or !in 0..9 ->.
Can I use if without else as an expression?
No. val s = if (a > 2) "big" stops with 'if' must have both main and 'else' branches when used as an expression. Add an else, or, if a missing value is fine, write else null and make the variable nullable. An if used as a plain statement needs no else.
When does a when need an else branch?
When it gives a value and its branches do not already cover every input. Over an Int or a String that means always. Over an enum, a sealed class or interface, or a Boolean, listing every case is enough, and it is safer than else: add a new case later and the compiler flags each when that misses it.
Run it yourself
Open any of these in the full Kotlin editor to tweak, run and share.
Kotlin playground