package com.learn.scala.day12
import WeekDayEnum._
import com.learn.scala.day12.ColorEnum._
/**
* scala没有枚举类型,但是可以通过实现Enumeration实现枚举,
* Created by zhuqing on 2017/3/5.
*/
object Day12EnumTest {
def main(args: Array[String]): Unit = {
/**
* 遍历枚举
*/
for (gender <- GenderEnum.values) {
println(gender.id + "," + gender)
}
for (color <- ColorEnum.values) {
println(color.id + "," + color)
}
for (weekday <- WeekDayEnum.values) {
println(weekday.id + "," + weekday)
}
/**
* 使用枚举
*/
println(GenderEnum.MAN)
/**
* 直接时候枚举名,需要
* 1.导入枚举import com.learn.scala.day12.WeekEnum._
*/
println(MONDAY)
println(RED+"="+RED.id)
}
}
枚举实现:
package com.learn.scala.day12
/**
* scala没有枚举类型,但是可以通过实现Enumeration实现枚举,
* 枚举必须是object的
* 枚举类命名是最好以Enum结尾
* 性别的枚举,
*/
object GenderEnum extends Enumeration {
/**
* 使用默认value,枚举的id从0开始累加1
* value的Name默认是枚举
*/
val MAN, WOMAN, MAN_TO_WOMAN, WOMAN_To_MAN, UNKNOW = Value
}
object ColorEnum extends Enumeration {
/**
* 自定义Value的Id,name
*/
val RED = Value(0xff0000, "红")
val GREEN = Value(0x00ff00, "绿")
val BLUE = Value(0x0000ff, "蓝")
}
object WeekDayEnum extends Enumeration {
/**
* 自定义Value的Id
*/
val MONDAY = Value(1)
/**
* 没有自定义Value的Id,Id值会根据上一个定义的值+1
*/
val TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = Value
}