I have a method to compare two byte arrays. The code is java-style, and there are many “if-else”s.
def assertArray(b1: Array[Byte], b2: Array[Byte]) {
if (b1 == null && b2 == null) return;
else if (b1 != null && b2 != null) {
if (b1.length != b2.length) throw new AssertionError("b1.length != b2.length")
else {
for (i <- b1.indices) {
if (b1(i) != b2(i)) throw new AssertionError("b1(%d) != b2(%d)".format(i, i))
}
}
} else {
throw new AssertionError("b1 is null while b2 is not, vice versa")
}
}
I have tried as following, but it’s not simplified the code much:
(Option(b1), Option(b2)) match {
case (Some(b1), Some(b2)) => if ( b1.length == b2.length ) {
for (i <- b1.indices) {
if (b1(i) != b2(i)) throw new AssertionError("b1(%d) != b2(%d)".format(i, i))
}
} else {
throw new AssertionError("b1.length != b2.length")
}
case (None, None) => _
case _ => throw new AssertionError("b1 is null while b2 is not, vice versa")
}
Unless you’re doing this as an academic exercise, how about
The description:
I will admit to this being ‘java style’ 🙂
Since you’re throwing AssertionErrors, you can remove all of the else’s:
If, as I suspect, you’re actually using this within JUnit tests (hence the assertArray), then you can use a trick which I often do, compare the string representations of the arrays:
which will give you the same outcome (an AssertionError), with where the differences are.