Scala用于理解/循环和类型化模式

时间:2017-04-23 09:41:54

标签: scala

根据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)}

没有错误。

1 个答案:

答案 0 :(得分:10)

您从规范中获得的翻译实际上是

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)
相关问题