https://kotlinlang.org logo
#getting-started
Title
# getting-started
r

Ray Rahke

02/24/2024, 2:07 PM
Copy code
val result = when {
    guess > answer -> "Lower!"
    guess < answer -> "Higher!"
    guess == answer -> "Yes!"
}
it says it is not exhaustive. it logically is.
h

Harold Martin

02/24/2024, 3:43 PM
What are the types of
guess
and
answer
?
r

Ray Rahke

02/24/2024, 3:50 PM
Int
c

Casey Brooks

02/24/2024, 3:55 PM
When blocks are currently pretty limited in determining when they're exhaustive. It really only supports enums, sealed classes, and Boolean values, but cannot determine when a set of expressions covers all cases. The fix is to add an
else ->
condition, or turn your final
==
condition into the
else
👍 1
r

Ray Rahke

02/24/2024, 3:56 PM
Yeah I figured that out. Just a bit of a shame it can't infer that already
readability suffers a bit here
c

Casey Brooks

02/24/2024, 3:57 PM
Furthermore, if you are using
when
without a subject, the branches are arbitrary expressions so you'll always need to provide an
else
. It can only be smart when it has a specific value it's checking conditions for (
when(guess)
), and then only in some specific circumstances
r

Ray Rahke

02/24/2024, 3:57 PM
yeah, but when(guess) doesn't have a supported syntax for this iirc
when (guess) { > answer ->
not a thing
e

ephemient

02/24/2024, 4:04 PM
it sort of exists, with some custom wrappers
Copy code
value class LessThan(val value: Int) {
    operator fun contains(other: Int): Boolean = other < value
}
value class GreaterThan(val value: Int) {
    operator fun contains(other: Int): Boolean = other > value
}

when (guess) {
    in LessThan(answer) -> ...
    in GreaterThan(answer) -> ...
    else -> ...
}
or using ranges such as
Int.MIN_VALUE..<answer
, but the compiler still requires
else