Guard conditions in when
suggest changeA guard condition adds an extra if check to a branch of a when with a subject:
when (x) {
is String if x.isEmpty() -> ...
}
The branch is taken only when the subject matches and the guard is true. Without guards you had to nest a second when or an if inside the branch. With guards all cases sit in one flat list.
Guards were a preview in Kotlin 2.1 (behind the -Xwhen-guards flag) and are stable since Kotlin 2.2. All examples here were compiled and run with Kotlin 2.4.21 on JDK 25, with no compiler flags.
For the basics of when see When-statement argument matching and When-statement as expression.
Basic syntax
Put if <condition> after the branch condition and before ->:
fun classify(x: Any): String = when (x) {
is String if x.isEmpty() -> "empty string"
is String -> "string of length ${x.length}"
is Int if x < 0 -> "negative int"
is Int -> "int"
else -> "something else"
}
fun main() {
for (x in listOf("", "hello", -5, 42, 3.14)) {
val shown = if (x is String) "\"$x\"" else x
println("$shown -> ${classify(x)}")
}
}
"" -> empty string
"hello" -> string of length 5
-5 -> negative int
42 -> int
3.14 -> something else
Points to note:
xis smart cast toStringinside the guard, sox.isEmpty()compiles. The same smart cast applies in the branch body.- Branches are still checked from top to bottom, and the first match wins. Put the guarded branch before the plain one for the same type. If
is String ->came first,is String if x.isEmpty()would never run. - The guard can be any
Booleanexpression. It can use&&,||and!without extra parentheses, and it can call functions or use other variables in scope.
Replacing nested when and if
Guards are most useful with a sealed hierarchy where some cases need a closer look. Here is how HTTP responses were handled before Kotlin 2.2, and the same logic with guards:
sealed interface Response
data class Ok(val body: String) : Response
data class Redirect(val location: String, val permanent: Boolean) : Response
data class Failure(val status: Int, val retryAfterSeconds: Int?) : Response
// Before Kotlin 2.2: a nested when inside one branch
fun handleOld(r: Response): String = when (r) {
is Ok -> if (r.body.isEmpty()) "no content" else "ok: ${r.body}"
is Redirect -> "follow ${r.location}"
is Failure -> when {
r.status == 429 && r.retryAfterSeconds != null ->
"retry in ${r.retryAfterSeconds * 1000} ms"
r.status >= 500 -> "server error ${r.status}, retry later"
else -> "client error ${r.status}"
}
}
// With guard conditions: one flat list of cases
fun handle(r: Response): String = when (r) {
is Ok if r.body.isEmpty() -> "no content"
is Ok -> "ok: ${r.body}"
is Redirect -> "follow ${r.location}"
is Failure if r.status == 429 && r.retryAfterSeconds != null ->
"retry in ${r.retryAfterSeconds * 1000} ms"
is Failure if r.status >= 500 -> "server error ${r.status}, retry later"
is Failure -> "client error ${r.status}"
}
fun main() {
val responses = listOf(
Ok(""), Ok("hello"), Redirect("/login", permanent = false),
Failure(429, 30), Failure(429, null), Failure(503, null), Failure(404, null),
)
for (r in responses) {
check(handle(r) == handleOld(r))
println("$r -> ${handle(r)}")
}
}
Ok(body=) -> no content
Ok(body=hello) -> ok: hello
Redirect(location=/login, permanent=false) -> follow /login
Failure(status=429, retryAfterSeconds=30) -> retry in 30000 ms
Failure(status=429, retryAfterSeconds=null) -> client error 429
Failure(status=503, retryAfterSeconds=null) -> server error 503, retry later
Failure(status=404, retryAfterSeconds=null) -> client error 404
Both versions give the same results (check would throw otherwise). The guarded version is easier to scan: every case is one line at the same level, and you can read off which cases exist without following nested blocks.
Smart casts from the guard also carry into the body. In the 429 branch the guard checks r.retryAfterSeconds != null, so in the body r.retryAfterSeconds is an Int, not an Int?, and * 1000 compiles. This works because retryAfterSeconds is a val of a class in the same module. An open property or one with a custom getter wouldn't be smart cast.
Guards with constants, enums and ranges
A guard can follow any kind of branch condition, not just is. With enum constants:
enum class Level { DEBUG, INFO, WARN, ERROR }
fun shouldLog(level: Level, verbose: Boolean, logger: String): Boolean = when (level) {
Level.DEBUG if verbose -> true
Level.DEBUG -> false
Level.INFO if logger.startsWith("org.apache") -> false
Level.INFO, Level.WARN, Level.ERROR -> true
}
fun main() {
println(shouldLog(Level.DEBUG, verbose = true, logger = "app"))
println(shouldLog(Level.DEBUG, verbose = false, logger = "app"))
println(shouldLog(Level.INFO, verbose = false, logger = "org.apache.http"))
println(shouldLog(Level.INFO, verbose = false, logger = "app"))
println(shouldLog(Level.ERROR, verbose = false, logger = "org.apache.http"))
}
true
false
false
true
true
There is no else here: every enum entry has an unguarded branch, so the when is exhaustive (more on that below). See When-statement with enums for more about when over enums.
With in ranges:
fun shippingCost(weightKg: Double, express: Boolean, country: String): Double = when (weightKg) {
in 0.0..1.0 if express -> 9.0
in 0.0..1.0 -> 4.5
in 1.0..10.0 if country != "PL" -> 15.0 + weightKg
in 1.0..10.0 -> 8.0
else -> 20.0 + weightKg * 2
}
fun main() {
println(shippingCost(0.5, express = true, country = "PL"))
println(shippingCost(0.5, express = false, country = "PL"))
println(shippingCost(3.0, express = false, country = "DE"))
println(shippingCost(3.0, express = false, country = "PL"))
println(shippingCost(12.0, express = false, country = "PL"))
}
9.0
4.5
18.0
8.0
44.0
The guard can test something other than the subject. Here the subject is the weight, and the guards look at express and country. That's what makes guards different from just writing a longer condition: the subject picks the group of cases, and the guard picks among them.
The same works with string constants. A when (val ...) subject keeps the value in scope for the guards:
fun run(line: String): String {
val args = line.trim().split(Regex("""\s+"""))
return when (val cmd = args[0].lowercase()) {
"get" if args.size == 2 -> "GET ${args[1]}"
"set" if args.size == 3 -> "SET ${args[1]} = ${args[2]}"
"get", "set" -> "usage: $cmd needs ${if (cmd == "get") 1 else 2} argument(s)"
"quit", "exit" -> "bye"
else if cmd.startsWith("#") -> "comment ignored"
else -> "unknown command: $cmd"
}
}
fun main() {
listOf("get name", "SET name Ann", "set name", "get", "exit", "# note", "del x")
.forEach { println("%-14s -> %s".format(it, run(it))) }
}
get name -> GET name
SET name Ann -> SET name = Ann
set name -> usage: set needs 2 argument(s)
get -> usage: get needs 1 argument(s)
exit -> bye
# note -> comment ignored
del x -> unknown command: del
This example also uses else if, covered next.
else if branches
else if <condition> -> is a branch that matches any subject, as long as the condition is true. It's handy for a catch-all check that has nothing to do with the branch conditions above it, like the # comment test in the previous example.
A guard on a constant branch can check something other than the subject and smart cast it. else if conditions work the same way:
data class Event(val name: String, val payload: Any?)
fun summarize(e: Event): String = when (e.name) {
"click" if e.payload is Pair<*, *> -> "click at ${e.payload.first},${e.payload.second}"
"key" if e.payload is Char && e.payload.isLetter() -> "letter ${e.payload.uppercaseChar()}"
"key" if e.payload is Char -> "key code ${e.payload.code}"
"scroll" if e.payload is Int -> "scroll ${e.payload} lines (${e.payload * 16}px)"
else -> "ignored ${e.name}"
}
fun main() {
println(summarize(Event("click", 10 to 20)))
println(summarize(Event("key", 'q')))
println(summarize(Event("key", '7')))
println(summarize(Event("scroll", -3)))
println(summarize(Event("scroll", null)))
}
click at 10,20
letter Q
key code 55
scroll -3 lines (-48px)
ignored scroll
The subject is the event name, and the guards check the payload type. In "key" if e.payload is Char && e.payload.isLetter(), the is Char check smart casts e.payload for the right side of && and for the body.
An else if branch never makes a when exhaustive, so you still need a final plain else (or full coverage of a sealed type or enum):
fun f(x: Any): String = when (x) {
is String if x.isEmpty() -> "empty"
else if x is Int -> "int"
}
e6.kt:1:25: error: 'when' expression must be exhaustive. Add an 'else' branch.
fun f(x: Any): String = when (x) {
^^^^
Evaluation order
A guard is evaluated only after its branch condition matched, and branches are tried in order. That matters when the guard is expensive or has side effects:
fun isAdmin(user: String): Boolean {
println(" checking isAdmin($user)")
return user == "root"
}
fun access(path: String, user: String): String = when (path) {
"/public" -> "allowed"
"/admin" if isAdmin(user) -> "allowed"
"/admin" -> "denied"
else if isAdmin(user) -> "allowed (admin)"
else -> "not found"
}
fun main() {
for ((path, user) in listOf("/public" to "ann", "/admin" to "ann", "/admin" to "root", "/x" to "bob")) {
println("$path $user")
println(" -> ${access(path, user)}")
}
}
/public ann
-> allowed
/admin ann
checking isAdmin(ann)
-> denied
/admin root
checking isAdmin(root)
-> allowed
/x bob
checking isAdmin(bob)
-> not found
For /public no guard runs. For /admin the first guard runs once; when it's false, the next branch "/admin" -> matches without calling isAdmin again. For /x only the else if guard runs.
Exhaustiveness
The compiler checks that a when used as an expression, or a when statement over a sealed type, enum or Boolean, covers every case. A guarded branch doesn't count toward that. The compiler can't know when the guard is true, so it treats the branch as possibly not matching:
sealed interface Shape
data class Circle(val radius: Double) : Shape
data class Rect(val width: Double, val height: Double) : Shape
fun nonExhaustive(s: Shape): String = when (s) {
is Circle if s.radius > 0 -> "circle"
is Rect -> "rect"
}
e1.kt:5:39: error: 'when' expression must be exhaustive. Add the 'is Circle' branch or an 'else' branch.
fun nonExhaustive(s: Shape): String = when (s) {
^^^^
The compiler doesn't analyze guards for completeness either. Two guards that together cover every value still don't make the when exhaustive:
fun describe(s: Shape): String = when (s) {
is Circle if s.radius == 0.0 -> "point"
is Circle if s.radius != 0.0 -> "circle"
is Rect -> "rect"
}
e12.kt:5:34: error: 'when' expression must be exhaustive. Add the 'is Circle' branch or an 'else' branch.
fun describe(s: Shape): String = when (s) {
^^^^
The fix is to make the last branch for each type unguarded, as in handle() above: is Circle if s.radius == 0.0 -> ... followed by is Circle -> .... Avoid fixing it with else. With an unguarded branch per subtype, adding a new subtype to a sealed hierarchy still gives a compile error everywhere it isn't handled. An else would quietly swallow the new case.
The same rules apply to enums and Boolean. This compiles because true and false both have an unguarded branch:
fun g(b: Boolean, x: Int): String = when (b) {
true if x > 0 -> "t+"
true -> "t"
false -> "f"
}
The compiler also doesn't warn when a guarded branch can never be reached. This compiles without a warning, even though is B if s.n > 0 comes after is B and never runs:
sealed interface S
data object A : S
data class B(val n: Int) : S
fun f(s: S): String = when (s) {
A -> "a"
is B -> "b"
is B if s.n > 0 -> "pos" // unreachable, no warning
}
Rules and restrictions
Only in when with a subject. A subject-less when already takes arbitrary Boolean conditions, so a guard would add nothing there:
fun f(x: Int): String = when {
x > 0 if x < 10 -> "small"
else -> "other"
}
e2.kt:2:11: error: guard statements are only allowed in 'when' with subject.
x > 0 if x < 10 -> "small"
^^^^^^^^^
Use && instead: x > 0 && x < 10 -> "small". You could also rewrite a guarded when (s) as a subject-less when with s is Circle && s.radius == 0.0, but then you lose exhaustiveness checking. A subject-less when always needs an else, even if its branches cover every subtype of a sealed type:
fun describe(s: Shape): String = when {
s is Circle && s.radius == 0.0 -> "point"
s is Circle -> "circle"
s is Rect -> "rect"
}
e11.kt:5:34: error: 'when' expression must be exhaustive. Add an 'else' branch.
fun describe(s: Shape): String = when {
^^^^
No guard on a branch with several conditions. Commas and guards can't be combined. Otherwise it would be unclear whether the guard applies to the last condition or to all of them:
fun f(s: Shape): String = when (s) {
is Circle, is Rect if s.hashCode() > 0 -> "x"
else -> "y"
}
e3.kt:5:24: error: use of comma in 'when' condition with guard statement is not allowed.
is Circle, is Rect if s.hashCode() > 0 -> "x"
^^^^^^^^^^^^^^^^^^^
Split it into two branches, or move the check into the body. Unguarded branches with commas, like "get", "set" -> above, are still fine in the same when.
Language version. Guards need language version 2.2 or newer. With an older -language-version (or languageVersion in Gradle) you get:
$ kotlinc t1.kt -language-version 2.1 -d out
warning: language version 2.1 is deprecated and its support will be removed in a future version of Kotlin. Update the version to 2.2.
t1.kt:6:15: error: the feature "when guards" is only available since language version 2.2
is Circle if s.radius == 0.0 -> "point"
^^^^^^^^^^^^^^^^^^
If a build still passes the old preview flag, the 2.4 compiler warns that it's no longer needed, and you can remove it:
warning: the argument '-Xwhen-guards' is redundant for the current language version 2.4.
See Compile and run Kotlin code in command line for more about compiler options.
When to use guards
- Use a guard when one case of a sealed type, enum or constant needs a sub-case. It keeps the
whenflat and keeps exhaustiveness checking. - Always end each type's group of branches with an unguarded branch rather than an
else, so new subtypes are caught at compile time. - If almost every branch needs a guard and the subject barely matters, a subject-less
whenwith&&(or anif/else ifchain, see When-statement instead of if-else-if chains) may read better. - If the same type check would be repeated with many guards, consider moving the logic into a method on the type instead. Polymorphism compares sealed hierarchies with
whenagainst virtual methods. - Keep guards cheap and free of side effects. They run in branch order and may not run at all.