为什么Scala for循环转换不等效?
我试着写这个代码为什么Scala for循环转换不等效?,scala,for-loop,Scala,For Loop,我试着写这个代码 val req: mutable.Buffer[InterfaceHttpData] = /*...*/ for (attr: Attribute <- req) { println(attr.getValue()) } 我已经通读了,据我所知,这个for循环应该与下面的内容等效 req.withFilter { case attr: Attribute => true; case _ => false }.foreach { case attr:
val req: mutable.Buffer[InterfaceHttpData] = /*...*/
for (attr: Attribute <- req) {
println(attr.getValue())
}
我已经通读了,据我所知,这个for循环应该与下面的内容等效
req.withFilter { case attr: Attribute => true; case _ => false }.foreach {
case attr: Attribute => println(attr.getValue())
}
这篇文章编译得很干净。我是否误解了for循环转换是如何完成的?根据规范,此转换仅在
p val c:List[c]=Nil中的p
时适用
c:List[c]=List()
scala>for(e:T val T:List[T]=Nil
t:List[t]=List()
scala>for(e:C单位
必需:T=>?
对于(e:C你在哪里读这篇文章?据我所知,模式的无可辩驳性只会影响withFilter
调用是否存在。不管怎样,我仍然不理解为什么你的上一个表达式中存在类型不匹配;因为e:C
对于t
的类型不是无可辩驳的,所以翻译应该是de>t.withFilter{case e:C=>true;case{=>false}.foreach{case e:C=>println(e)}
,不是吗?,无可辩驳的模式但你是对的,它仍然应该翻译(读得太快),也许这是一个问题,但在编译器/规范中……不,我的意思是你读到转换只适用于无可辩驳的模式,但从后续的评论中,我认为你已经明白了:)是的,这是一个编译器错误,请参阅重复问题的答案。有趣的是,这里的注释读取规范的同一部分也太快了。。。
req.withFilter { case attr: Attribute => true; case _ => false }.foreach {
case attr: Attribute => println(attr.getValue())
}
scala> trait T
defined trait T
scala> class C extends T
defined class C
scala> val c: List[C] = Nil
c: List[C] = List()
scala> for (e: T <- c) println(e)
scala> val t: List[T] = Nil
t: List[T] = List()
scala> for (e: C <- t) println(e)
<console>:14: error: type mismatch;
found : C => Unit
required: T => ?
for (e: C <- l) println(e)
^