William Reed
06/21/2021, 8:34 PMvar a = true
var b = false
when (a, b) {
true, true -> ...
true, false -> ...
false, true -> ...
false, false -> ...
}
is this the best alternative?
when {
a, !b -> ...
}
William Reed
06/21/2021, 8:35 PMNir
06/21/2021, 8:37 PMWilliam Reed
06/21/2021, 8:40 PMdarkmoon_uk
06/22/2021, 4:53 AMvar 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 smallVadim Kapustin
06/22/2021, 6:12 AMenum 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
when (BooleanPair(a, b)) {
BooleanPair.TrueTrue -> ...
BooleanPair.TrueFalse -> ...
BooleanPair.FalseTrue -> ...
BooleanPair.FalseFalse -> ...
}
CLOVIS
06/22/2021, 8:46 AMdarkmoon_uk
06/27/2021, 12:00 PMif
pattern can't be beaten for simplicity and efficiency?
if(a) {
if(b) {
// true, true case
} else {
// true, false case
}
} else {
if(b) {
// false, true case
} else {
// false, false case
}
}
CLOVIS
06/27/2021, 12:22 PMCLOVIS
06/27/2021, 12:25 PMwhen {
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.