Unable to iterate over enumeration

Here is an example from Scala's Programming Book

object Color extends Enumeration { //val Red, Green, Blue = Value val Red = Value("Red") val Green = Value("Green") } for (d <- Color) print(d + " ") //Error value foreach is not a member of // object xxx.Color 

I have the latest version of Scala. Is this the cause of the error?

+8
scala
source share
2 answers

It should be:

 for (d <- Color.values) print(d + " ") 

Enumeration used the foreach method, so it worked only for (d <- Color) . But it is outdated and then deleted.

+17
source share

There is no foreach method in the Enumeration class. If you want to iterate over values, you must use the values method. So, for (d <- Color.values) print(d + " ") will print Red Green as you expect. Take a look at the documentation for the Enumeration class http://www.scala-lang.org/api/current/index.html#scala.Enumeration

0
source share

All Articles