Iterate enumerated class instances

夙愿已清 提交于 2019-12-20 02:12:51

问题


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?


回答1:


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.




回答2:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!