since something like this doesn’t work in kotlin ...
# announcements
w
since something like this doesn’t work in kotlin
Copy code
var a = true
var b = false
when (a, b) {
   true, true -> ...
   true, false -> ...
   false, true -> ...
   false, false -> ...
}
is this the best alternative?
Copy code
when {
   a, !b -> ...
}
also the first example probably isn’t the most readable with boolean values tossed in
n
you could make a and b into a pair and then match on that
🙌 2
w
good idea
d
Copy code
var a = true
var b = false
when (a to b) {
   true to true -> ...
   true to false -> ...
   false to true -> ...
   false to false -> ...
   else -> throw Exception("Unhandled a/b combo")
}
...sadly some
else
handling required, but other than that, aesthetic change is quite small
v
without else: we can make enum class
Copy code
enum class BooleanPair(val a: Boolean, val b: Boolean) {
    TrueTrue(true, true), TrueFalse(true, false),
    FalseTrue(false, true), FalseFalse(false, false);

    companion object {
        operator fun invoke(a: Boolean, b: Boolean) = values().first {
            it.a == a && it.b == b
        }
    }
}
and then
Copy code
when (BooleanPair(a, b)) {
    BooleanPair.TrueTrue -> ...
    BooleanPair.TrueFalse -> ...
    BooleanPair.FalseTrue -> ...
    BooleanPair.FalseFalse -> ...
}
c
What are you trying to do exactly? All of this seems over-engineered
👎 1
d
@CLOVIS Although I made one of the suggestions above, I agree with you. Surely this good old
if
pattern can't be beaten for simplicity and efficiency?
Copy code
if(a) {
    if(b) {
        // true, true case
    } else {
        // true, false case
    }
} else {
    if(b) {
        // false, true case
    } else {
        // false, false case
    }
}
c
Exactly. Maybe there's even a simpler solution, but we'd need to know more of the context.
Honestly even
Copy code
when {
  a && b ->
  a && !b ->
  !a && b ->
  !a && !b ->
}
is simple, short, and readable. Sure, it's not pattern matching and it's a little bit of boilerplate, but it's damn efficient and you probably don't need to write this often. If you do need to write this often, maybe there's another thing to be simplified elsewhere.