Best replacement of .deep method in Scala 2.13

Viewed 534

Since .deep method is been removed since Scala 2.13 What would be the best way to compare two Arrays that would work same as .deep? Example:(Before Scala 2.13, it would work as follows)

 scala> Array(Array(1),2).deep == Array(Array(1),2).deep
 res3: Boolean = true

One preferred solution is to use sameElements method, but this method does not work if the Array is nested. Example:

scala> Array(Array(1),2) sameElements Array(Array(1),2)
res0: Boolean = false

Note: I'm using Scala 2.13.3

2 Answers

If you're only interested in equality and you're dealing with native arrays you can use java.util.Arrays.deepEquals, which is documented here.

Quoting the documentation:

Returns true if the two specified arrays are deeply equal to one another. Unlike the equals(Object[],Object[]) method, this method is appropriate for use with nested arrays of arbitrary depth.

Two array references are considered deeply equal if both are null, or if they refer to arrays that contain the same number of elements and all corresponding pairs of elements in the two arrays are deeply equal.

Two possibly null elements e1 and e2 are deeply equal if any of the following conditions hold:

  • e1 and e2 are both arrays of object reference types, and Arrays.deepEquals(e1, e2) would return true
  • e1 and e2 are arrays of the same primitive type, and the appropriate overloading of Arrays.equals(e1, e2) would return true.
  • e1 == e2
  • e1.equals(e2) would return true.

Note that this definition permits null elements at any depth.

If either of the specified arrays contain themselves as elements either directly or indirectly through one or more levels of arrays, the behavior of this method is undefined.

@stefanobaghino solution is good.

But if you don't have Array[Object] but other type like e.g. Array[Byte], it could be better Objects.deepEquals(), that allows any Array type to be used.

Related