原创转载请注明出处:http://agilestyle.iteye.com/blog/2334476
Scala中创建一个枚举类型,通常需要定义一个object继承Enumeration抽象类
package org.fool.scala.enumeration
object Level extends Enumeration {
type Level = Value
val Overflow, High, Medium, Low, Empty = Value
}
object EnumerationTest extends App {
println(Level.Medium)
println(Level(0))
println(Level(Level.maxId - 1))
for (n <- Range(0, Level.maxId))
println((n, Level(n)))
// Vector((0,Overflow), (1,High), (2,Medium), (3,Low), (4,Empty))
println({
for (n <- Range(0, Level.maxId))
yield (n, Level(n))
})
// Vector(Overflow, High, Medium, Low, Empty)
println({
for (level <- Level.values)
yield level
}.toIndexedSeq)
def checkLevel(level: Level.Level) = level match {
case Level.Overflow => ">>> Overflow!"
case Level.Empty => "Alert: Empty"
case other => s"Level $level OK"
}
println(checkLevel(Level.Low))
println(checkLevel(Level.Empty))
println(checkLevel(Level.Overflow))
}
Note:
创建object不会以创建class的方式创建新类型,如果想将其当做类型处理,那么必须使用type关键字,比如将Enumeration的Value起一个新的名字Level作为别名
Console Output

本文介绍了Scala中如何创建枚举类型,并通过一个具体例子展示了枚举类型的定义与使用方法,包括值的获取、匹配等。
471

被折叠的 条评论
为什么被折叠?



