00008 Scala Enumerations
Enumeration应该算是程序语言里面比较通用的一个类型,在scala中也存在这样的类型, 我们看下Enumeration的定义:
abstract class Enumeration (initial: Int) extends Serializable Enumeration是一个抽象类,它定义四个value方法,来设置内部的值, 四个value方法如下定义:
/** Creates a fresh value, part of this enumeration. */
protected final def Value: Value = Value(nextId)
/** Creates a fresh value, part of this enumeration, identified by the
* integer `i`.
*
* @param i An integer that identifies this value at run-time. It must be
* unique amongst all values of the enumeration.
* @return Fresh value identified by `i`.
*/
protected final def Value(i: Int): Value = Value(i, nextNameOrNull)
/** Creates a fresh value, part of this enumeration, called `name`.
*
* @param name A human-readable name for that value.
* @return Fresh value called `name`.
*/
protected final def Value(name: String): Value = Value(nextId, name)
/** Creates a fresh value, part of this enumeration, called `name`
* and identified by the integer `i`.
*
* @param i An integer that identifies this value at run-time. It must be
* unique amongst all values of the enumeration.
* @param name A human-readable name for that value.
* @return Fresh value with the provided identifier `i` and name `name`.
*/
protected final def Value(i: Int, name: String): Value = new Val(i, name)知道如何设置Enum的值后,我们就可以尝试创建一个Enum了。
上面的例子中,我们创建了一个Enum,并且设置了几个值。
下面我们看下怎么取到Enum的值:
你可以看到如下的输出:
下面是怎么输出Enum的id:
结果如下:
怎么输出所有的Enum项呢?
输出结果如下:
接下来,我们看下怎么打印出所有的Enum:
输出如下:
最后,我们看下怎么改变Enum值的顺序:
输出结果如下:
最后更新于
这有帮助吗?