Scala模式匹配和类型推断

有人可以解释为什么以下代码编译?

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

这给了我关于类型擦除的(预期)警告,但它仍然编译.我希望这会抛出一个类型错误,就像我匹配“foo”而不是Option(“foo”)一样.

谢谢!

解决方法

代码评论,所以让我们花一点时间来品味:

/** 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.
   */

例如,请注意,None不是最终的.我知道,对吧?

如果您尝试使用scalac -Ypatmat-debug,则此处的注释可能有所帮助:

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

可达性几乎可达到:

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

但我没有看到任何可能有一天会被警告的承诺.出于性能原因?还可以说,为什么要警告一个实例[Foo [_]]?

目前,规范部分8.2 – 8.4激发了为什么与Foo [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 { ... }

相关文章

共收录Twitter的14款开源软件,第1页Twitter的Emoji表情 Tw...
Java和Scala中关于==的区别Java:==比较两个变量本身的值,即...
本篇内容主要讲解“Scala怎么使用”,感兴趣的朋友不妨来看看...
这篇文章主要介绍“Scala是一种什么语言”,在日常操作中,相...
这篇文章主要介绍“Scala Trait怎么使用”,在日常操作中,相...
这篇文章主要介绍“Scala类型检查与模式匹配怎么使用”,在日...