[英]Scala for comprehensions/loops and typed patterns
根据Scala语言规范的第6.19节,这个for循环:
for (e <-p) e'
被翻译成:
p <- e.withFilter{case p => true; case _ => false}.foreach{case p => e′}
那么,为什么这个小程序:
object ForAndPatterns extends App {
class A()
class B() extends A
val list: List[A] = List(new A(), new B(), new B())
for {b: B <- list}
println(b)
}
给出了这个编译错误:
Error:(7, 13) type mismatch;
found : proves.ForAndPatterns.B => Unit
required: proves.ForAndPatterns.A => ?
for {b: B <- list}
当这个表达式:
list.withFilter{case a: B => true; case _ => false}.foreach{case b => println(b)}
没有错误。
实际上,您从规范中获得的翻译
list.withFilter{case b: B => true; case _ => false}.foreach{case b: B => println(b)}
但它仍然编译和工作。 看起来Scala正在失去这个case
并转化为
list.withFilter{case b: B => true; case _ => false}.foreach{b: B => println(b)}
会产生同样的错误。
事实证明这是一个已知的旧bug: https : //github.com/scala/bug/issues/900 。
解决方法提供:
object Typed { def unapply[A](a: A) = Some(a) }
for { Typed(b: B) <- list } println(b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.