Anyone have any idea what's going on here? I am cl...
# getting-started
r
Anyone have any idea what's going on here? I am clearly handling every branch but am getting an exhaustive when error
This is a compiler error as well as showing in IDEA
j
Exhaustiveness cannot be detected for every possible type. Just for types that can be enumerated "easily" at compile time. The
Pair<Boolean, Boolean>
type is kinda like
Pair<T, U>
, and is not supported for this. You'll get exhaustiveness for enums and sealed classes, mostly.
r
wow, TIL! That's kinda nuts for such a foundational use case
In this case, what is best practice for a type-safe when over a set of booleans?
j
Could you please expand on your use case for a set of booleans?
r
In this specific scenario, I'm generating a string from a pair of bools (as in the example). In swift I'd do something like:
Copy code
switch (isSuccess, isRemote) {
  case (true, true): return "Great! Your request was successful"
  case (true, false): return "Great! Your remote request was successful"
  case (false, true): return "Oh no, your request failed"
  case (false, false): return "Oh no, your remote request failed"
}
Now there are of course many ways you could generate this string, but this kind of approach is extremely clear and avoids awkward string interpolation
k
In Swift, tuples are built into the language, so the compiler understands them. By contrast, in Kotlin, tuples are part of the library, so the compiler won't be able to automatically process them unless it did a lot of analysis on the
Pair
class that the library defines. I've often got around this by using nested
if/else
or by adding
else -> error("Impossible")
, neither of which look good.
r
funny, I thought this would work:
Copy code
val baz = when {
    isFoo && isBar -> "Lorem"
    !isFoo && isBar -> "Ipsum"
    isFoo && !isBar -> "Dolor"
    !isFoo && !isBar -> "Sit"
}
However, it gives the
'when' expression must be exhaustive
error on the
when
, AND it gives a warning that the last branch (
!isFoo && !isBar
) is always true 😅 . Replacing the last branch with
else
fixes both the error and the warning...
r
Yeah, it seems like adding an else -> error("compiler dumb") branch is the best approach, but I would have thought that in an expressive language like Kotlin there would have been a way to do this in a type safe way
c
Actually, because the last condition is always true, replacing it with
else
makes most sense to me. Add the comment at that line that it is the only remaning case.
e
there's two different things here: the compiler has a limited set of things it'll process for exhausting checking, and the IDE can spend more time and background work to show you that warning
💡 1
âž• 2