Lukasz Madon
Lukasz Madon

Reputation: 14994

Cannot iterate over Enumeration

Here is an example from book Programming in Scala

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 latest version of Scala. Is it the reason for error?

Upvotes: 11

Views: 9035

Answers (2)

Vladimir
Vladimir

Reputation: 499

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

Upvotes: 1

R&#233;gis Jean-Gilles
R&#233;gis Jean-Gilles

Reputation: 32719

This should be:

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

There used to be a foreach method in Enumeration, which is why doing just for (d <- Color) worked. But it has been deprecated, and then removed.

Upvotes: 20

Related Questions