When comparing two arrays for equality, use
sameElements
rather than==
.
==
does not compare arrays for value equality, but for reference equality.
This gives us the following counter-intuitive behaviour:
Array(1) == Array(1)
// res0: Boolean = false
This is because Array
is essentially an alias for Java’s array, which implements equals
as reference equality - only returning true
if two variables point to the same array instance.
sameElements
, on the other hand, has the behaviour you’d expect:
Array(1) sameElements Array(1)
// res1: Boolean = true
An alternative to sameElements
is calling deep
on each array before comparison:
Array(1).deep == Array(1).deep
// res2: Boolean = true
This is not the preferred solution because it’s slightly more expensive, creating instances that will be discarded immediately.
Linter | Rule |
---|---|
Scapegoat |
|
WartRemover |