what's the idiomatic way to check if 3 or 4 or eve...
# getting-started
k
what's the idiomatic way to check if 3 or 4 or even more variables are all the same? something like a == b == c == d ... ?
c
Not really super clean or idiomatic, but maybe something like :
Copy code
val allSame = listOf(a, b, c, d).distinct().size == 1
// or
val allSame = listOf(a, b, c, d).zipWithNext().all { (first, second) -> first == second }
Otherwise, you'd have to chain the individual checks in some way (
a == b && b == c
etc.)
k
Thanks, let's stuff everything in a list and see 🙂 It's inside a hot loop, might be too slow in the end...
d
Copy code
setOf(a, b, c, d).size == 1
🙌 1
j
I might ask why you’re trying to do this, the usage might inform the cleaner syntax. If you’ve a known value for
a
and you want to check that
b
,
c
and
d
are equal to it, then I see no problem with
(a == b && a == c && a == d)
. It’s clear what it means, maintainable (you can remove any check without having to stitch back the chain). It’s also most efficient to execute because of short-circuiting, though that probably doesn’t matter so much in this case.
âž• 2
j
sequenceOf(b, c, d).all{it == a}
🤔 1