Scala: strange behavior in matching `for` patterns for the None case

Strange behavior in matching for patterns:

 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 does the second example produce two outputs of 'none' ? This example may be synthetic and impractical, but this behavior is not expected. Is this a bug or feature?

+6
source share
2 answers

What you know is the error:

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 

Spectrum in smart:

http://www.scala-lang.org/files/archive/spec/2.11/06-expressions.html#for-comprehensions-and-for-loops

Compare the purpose of the intermediate stream that does not display an error:

 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 
+8
source

This is because None interpreted as a variable name:

 scala> for (None <- a) { println(None) } Some(1) None 

Here is a simplified example without for :

 scala> val None = 5 None: Int = 5 scala> val Some(a) = Some(5) a: Int = 5 
+4
source

All Articles