...">

Scala pattern matching and type inference

Can someone explain why the following code compiles?

Option("foo") match {
  case x: List[String] => println("A")
  case _ => println("B")
}

This gives me a (expected) warning about erasing styles, but it still compiles. I expected this to throw a type error as if I matched with "foo"instead Option("foo").

Thank!

+5
source share
3 answers

The code is commented out, so let's think that:

  /** If we can absolutely rule out a match we can fail early.
   *  This is the case if the scrutinee has no unresolved type arguments
   *  and is a "final type", meaning final + invariant in all type parameters.
   */

Note that None is not final, for example. I know, right?

If you ever try scalac -Ypatmat-debug, a comment here might help:

https://github.com/scala/scala/pull/650

Reachability is almost achievable:

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

promises , - . ? , Of [Foo [_]]?

8.2 - 8.4 , Foo [a] (- a). , . .

trait Foo[+A]
final class Fuzz[+A] extends Foo[A]
final object Fooz extends Foo[Nothing]
object Futz extends Foo[Nothing]

//error
Fooz match {
  case x: List[_] => println("A")
  case _ => println("B")
}
//no error
Futz match { ... }
+4

, Option, List Product, . , . , :

scala> Option("foo") match {
 | case x: Tuple2[String,String] => println("TUPLE")
 | case x: List[String] => println("LIST")
 | case _ => println("OTHER")
 | }
<console>:9: warning: non variable type-argument String in type pattern (String, String)       is unchecked since it is eliminated by erasure
          case x: Tuple2[String,String] => println("TUPLE")
                  ^
<console>:10: warning: non variable type-argument String in type pattern List[String] is unchecked since it is eliminated by erasure
          case x: List[String] => println("LIST")
                  ^

UPDATE w/r/t case classes (- ):

scala> case class Foo(bar: Int)
defined class Foo

scala> val y: Product = Foo(123)
y: Product = Foo(123)
+2

I noticed that an error is displayed when the class of the value being matched is declared final (and we know what Stringis final). I still don’t know why there are no mistakes without him.

0
source

All Articles