Scala:无情况下`for`模式匹配中的奇怪行为 [英] Scala: strange behavior in `for` pattern matching for None case
本文介绍了Scala:无情况下`for`模式匹配中的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
for
循环模式匹配中的奇怪行为:
Strange behavior in for
cycle pattern matching:
scala> val a = Seq(Some(1), None)
a: Seq[Option[Int]] = List(Some(1), None)
scala> for (Some(x) <- a) { println(x) }
1
scala> for (None <- a) { println("none") }
none
none
为什么在第二个示例中产生了两个输出 'none'
?也许这个例子是合成的,不实用,但这种行为是不可预期的.这是错误还是功能?
Why in second example two output 'none'
produced? Maybe this example is synthetic and not practical, but such behavior is not expectable. Is this bug or feature?
推荐答案
你知道吗,这是一个错误:
What do you know, it is a bug:
https://issues.scala-lang.org/browse/SI-9324
scala> val vs = Seq(Some(1), None)
vs: Seq[Option[Int]] = List(Some(1), None)
scala> for (n @ None <- vs) println(n)
None
不明确的规范:
比较没有出现错误的中游分配:
Compare midstream assignment, which does not exhibit the bug:
scala> for (v <- vs; None = v) println(v)
scala.MatchError: Some(1) (of class scala.Some)
at $anonfun$1.apply(<console>:9)
at $anonfun$1.apply(<console>:9)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:245)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:245)
at scala.collection.immutable.List.foreach(List.scala:381)
at scala.collection.TraversableLike$class.map(TraversableLike.scala:245)
at scala.collection.immutable.List.map(List.scala:285)
... 33 elided
这篇关于Scala:无情况下`for`模式匹配中的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文