println("A") case _ => println(-6ren">
gpt4 book ai didi

Scala 模式匹配和类型推断

转载 作者:行者123 更新时间:2023-12-04 18:47:14 24 4
gpt4 key购买 nike

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

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

但我没有看到任何关于有朝一日可能会发出警告的 promise 。出于性能原因?也可以说,为什么要警告 instanceOf[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 { ... }

关于Scala 模式匹配和类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12342074/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com