用于理解/循环和类型化模式的 Scala [英] Scala for comprehensions/loops and typed patterns
本文介绍了用于理解/循环和类型化模式的 Scala的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
根据 Scala 语言规范的第 6.19 节,此 for 循环:
According to section 6.19 of the Scala Language Specification this for loop:
for (e <-p) e'
被翻译成:
p <- e.withFilter{case p => true; case _ => false}.foreach{case p => e′}
那么,为什么这个小程序:
So, why this small program:
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)}
不会出错.
推荐答案
你从规范中得到的翻译实际上是
The translation you get from specification is actually
list.withFilter{case b: B => true; case _ => false}.foreach{case b: B => println(b)}
但它仍然可以编译和工作.似乎 Scala 正在丢失 case
并转换为
but it still compiles and works. It seems like Scala is losing the case
and translating to
list.withFilter{case b: B => true; case _ => false}.foreach{b: B => println(b)}
这会产生同样的错误.
事实证明这是一个已知的旧错误:https://github.com/scala/bug/issues/900.
This turns out to be a known and old bug: https://github.com/scala/bug/issues/900.
那里提供的解决方法:
object Typed { def unapply[A](a: A) = Some(a) }
for { Typed(b: B) <- list } println(b)
这篇关于用于理解/循环和类型化模式的 Scala的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文