45.scala编程思想笔记——枚举

152 阅读1分钟

45.scala编程思想笔记——枚举

欢迎转载,转载请标明出处:blog.csdn.net/notbaron/ar…
源码下载连接请见第一篇笔记。\

枚举是名字的集合。

Scala的Enumeration类提供 了一种管理这些名字的便捷方式。

要想创建一个枚举,通常需要将Enumeration类继承到object.

例如:

import com.atomicscala.AtomicTest._

 

object Level extends Enumeration {

  type Level =Value

  val Overflow,High, Medium,

      Low,Empty = Value

}

 

Level.Medium is "Medium"

import Level._

Medium is "Medium"

 

{ for(n <- Range(0, Level.maxId))

    yield (n,Level(n)) } is

  Vector((0,Overflow), (1, High),

    (2,Medium), (3, Low), (4, Empty))

 

{ for(lev <- Level.values)

    yield lev}.toIndexedSeq is

 Vector(Overflow, High,

    Medium,Low, Empty)

 

def checkLevel(level:Level)= level match {

  case Overflow=> ">>> Overflow!"

  case Empty=> "Alert: Empty"

  case other=>  s"Level $level OK"

}

 

checkLevel(Low) is "Level Low OK"

checkLevel(Empty) is "Alert: Empty"

checkLevel(Overflow) is ">>>Overflow!"

其中Enumeration中的名字表示各种不同的级别。