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

Karlo Lozovina

02/03/2022, 4:21 PM
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

Casey Brooks

02/03/2022, 4:30 PM
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

Karlo Lozovina

02/03/2022, 4:33 PM
Thanks, let's stuff everything in a list and see 🙂 It's inside a hot loop, might be too slow in the end...
d

dmitriy.novozhilov

02/03/2022, 6:36 PM
Copy code
setOf(a, b, c, d).size == 1
🙌 1
j

jwass

02/03/2022, 8:23 PM
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

Jacob

02/03/2022, 9:41 PM
sequenceOf(b, c, d).all{it == a}
🤔 1
2 Views