I was going through some exercises and noticed the following behavior for matching of tuple2. Is there a particular reason for this?
def test(x: Any): Unit= x match{
case i: Int => println("int")
case b: Boolean => println("bool")
case ti: (_, Int) => println("tuple2 with int")
case tb: (_, Boolean)=> println("tuple2 with boolean")
case _ => println("other")
}
test(false) //prints bool
test(3) ///prints int
test((1,3)) //prints tuple with int
test((1,true)) //prints tuple with int
If i exchange the ti and tb cases, then the (1,3) prints tuple2 with boolean. I assume there is some type casting going on here, but I’m unclear why.
Can someone give me a quick explanation.
Thanks
Type erasure. It can’t tell what the types are inside the
Tupleat runtime. It will compile fine, but it should emit a warning. This is what happens when I do it in:pastemode in the REPL:Notice the last warning, it says the
(_, Boolean)is unreachable because the(_, Int)will match on everyTuple2, courtesy of type erasure.