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")
}