Scala模式匹配和类型推断
发布时间:2020-12-16 18:18:20 所属栏目:安全 来源:网络整理
导读:有人可以解释为什么以下代码编译? Option("foo") match { case x: List[String] = println("A") case _ = println("B")} 这给了我关于类型擦除的(预期)警告,但它仍然编译.我希望这会抛出一个类型错误,就像我匹配“foo”而不是Option(“foo”)一样. 谢谢!
有人可以解释为什么以下代码编译?
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 { ... } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |