Is there a simple way to iterate over all enumerated instances of a class in Ceylon?
Just like values()
for Java enums?
abstract class Suit() of hearts | diamonds | clubs | spades {
shared formal String name;
}
object spades extends Suit() { name => "Spades"; }
object clubs extends Suit() { name => "Clubs"; }
object diamonds extends Suit() { name => "Diamonds"; }
object hearts extends Suit() { name => "Hearts"; }
Lets say I'd like to pick a random suit or I'd like to print all suits by their names.
Edit:
Explicitly adding all suits to an iterable works but we have to list all possible values again.
{Suit+} suits = {spades, clubs, diamonds, hearts};
Can somebody come up with something better?
This can be done now with ClassOrInterface.caseValues
:
Suit[] suits = `Suit`.caseValues;
Regarding the returned sequence:
This sequence is ordered and skips any case type to only include case values.
One way is to use the metamodel:
for (caseType in `class Suit`.caseTypes) {
assert (is OpenClassOrInterfaceType caseType);
print(caseType.declaration.name);
}
来源:https://stackoverflow.com/questions/19402031/iterate-enumerated-class-instances