Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot iterate over Enumeration

Tags:

scala

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?

like image 859
Lukasz Madon Avatar asked Jun 11 '13 12:06

Lukasz Madon


People also ask

Can you iterate over enum?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.

Can you loop through an enum C ++?

Can you loop through an enum C ++? Yes. It iterates over an std::initializer_list<Item>.

Is enum an iterable?

Enumeration is like an Iterator , not an Iterable . A Collection is Iterable . An Iterator is not.


1 Answers

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.

like image 136
Régis Jean-Gilles Avatar answered Oct 05 '22 17:10

Régis Jean-Gilles