Mixing typed matches with sequence matching produces weird behavior in Scala

I'm trying to figure out what is going on on this piece of code, trying to figure out if there is something that I don’t understand, or if it is a compiler error or an unintuitive specification, let's define these two almost identical functions

def typeErause1(a: Any) = a match { case x: List[String] => "stringlists" case _ => "uh?" } def typeErause2(a: Any) = a match { case List(_, _) => "2lists" case x: List[String] => "stringlists" case _ => "uh?" } 

now, if I call typeErause1(List(2,5,6)) , I get "stringlists" because even if it is actually a List[Int] with an erase type, it cannot tell the difference. But it is strange if I call typeErause2(List(2,5,6)) , I get "uh?" , and I don’t understand why it does not match List[String] , as it was before. If I use List[_] instead in the second function, it will be able to match it correctly, which makes me think that this is a bug in scalac.

I am using Scala 2.9.1

+6
source share
1 answer

This is a coincidence error;) Pattern matching (was?) Rewritten for 2.10

I just checked with the last night and your code works as expected:

 Welcome to Scala version 2.10.0-20120426-131046-b1aaf74775 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_31). Type in expressions to have them evaluated. Type :help for more information. scala> def typeErause1(a: Any) = a match { | case x: List[String] => "stringlists" | case _ => "uh?" | } warning: there were 2 unchecked warnings; re-run with -unchecked for details typeErause1: (a: Any)String scala> def typeErause2(a: Any) = a match { | case List(_, _) => "2lists" | case x: List[String] => "stringlists" | case _ => "uh?" | } warning: there were 3 unchecked warnings; re-run with -unchecked for details typeErause2: (a: Any)String scala> typeErause1(List(2,5,6)) res0: String = stringlists scala> typeErause2(List(2,5,6)) res1: String = stringlists 
+1
source

Source: https://habr.com/ru/post/912672/


All Articles