Scala:`for`模式匹配中的奇怪行为无情况 [英] Scala: strange behavior in `for` pattern matching for None case
本文介绍了Scala:`for`模式匹配中的奇怪行为无情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
scala>在 val a = Seq(Some(1),None)
a:Seq [Option [Int]] = List(一些(1),None)
scala> for(Some(x)< -a){println(x)}
1
scala> for(None< - a){println(none)}
none
none
为什么在第二个例子中产生两个输出'none'
?也许这个例子是合成的而不实际的,但是这样的行为是不可预期的。这个bug或者特性是什么?
解决方案
你知道吗,这是一个bug:
https://issues.scala-lang.org/browse/SI -9324
scala> val vs = Seq(一些(1),无)
vs:Seq [Option [Int]] = List(一些(1),无)
scala> for(n @ None <-vs)println(n)
None
在umambiguous:
比较中间分配,不会显示错误:
阶> (v <-vs; None = v)println(v)
scala.MatchError:一些(1)(类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)
在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
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
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
The spec in umambiguous:
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屋!
查看全文