Is it a bug in Scala 2.8.0 ? (the same happens with 2.8.1.RC2)
import junit.framework._
import Assert._
class BugTest extends TestCase {
def compare(first: Any, second: Any): Int = {
(first, second) match {
case (k: Int, o: Int) => k compare o
//why the next case matches (Float, Int) but does not match (Int, Float) ???
case (k: Number, o: Number) => k.doubleValue() compare o.doubleValue()
case _ => throw new Exception("Unsupported compare " + first + "; " + second)
}
}
def testCompare() {
assertEquals("Both Int", -1, compare(0, 1))
assertEquals("Both Float", 1, compare(1.0, 0.0))
assertEquals("Float then Int", 0, compare(10.0, 10))
assertEquals("Int then Float", 0, compare(10, 10.0))//this fails with an exception
}
}
I think this is a bug. If you look at the generated bytecode:
In line 6, the check is done whether the first variable is an instance of
java.lang.Integer. If this does not succeed, we continue at line 81, which starts with thejava.lang.Numbercheck. If the first variable is an Integer, then we continue with the same check for the second variable. However, if this second check does not succeed, instead of again continuing at line 81 with the Number check, a jump is made to line 45, which throws the Exception. That does not seem to be correct. I quickly browsed through trac but couldn’t directly find an issue regarding this, so it may be sensible to create one.Edit
As Extempore pointed out, it is a bug that is already in trac, see his comment below.