Matching order with extractor

I defined a custom extractor to get the last element of the list, as in https://stackoverflow.com/a/212960/212 :

object :+ { def unapply[A](l: List[A]): Option[(List[A], A)] = { if (l.isEmpty) None else Some(l.init, l.last) } } 

Now this corresponds to "good":

 List(1, 2, 3) match { case init :+ last => "good" case head :: tail => "bad" } 

But if I add another sentence, it will suddenly become “bad”:

 List(1, 2, 3) match { case List(7) => "never" case init :+ last => "good" case head :: tail => "bad" } 

What is the reason for this behavior?

+6
source share
1 answer

This is # 1697/2337 and a dozen duplicates.

https://issues.scala-lang.org/browse/SI-1697

We can say with confidence that it will not be fixed directly, but by deleting the template for the implementation of virtpatmat. Try a recent build and compile with -Yvirtpatmat, you will get the correct answer.

+6
source

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


All Articles