Scala 中的 枚举类比较有用, 又和Java 不太一样,我们在这里整理一下。
枚举主要用于 表述语义更为清楚,例如,以下两个 变量 : ”7“ 与 MediaCode.SOHU, 肯定是 Media.SOHU 更容易被理解。
目录
1.基础案例
2.语法介绍
3.扩展函数
1.基础案例
基础的枚举, 示例如下:
package enumDefine
/**
* Created by szh on 2018/12/21.
*/
object EnumTest extends Enumeration {
type EnumTest = Value //声明枚举对外暴露的变量类型
val CC, CC2, CC3 = Value
val Q1 = Value(100, "Quarter1")
val Q2 = Value(200, "Quarter2")
def main(args: Array[String]): Unit = {
for (x <- EnumTest.values) {
println(s"${x.id} ${x}")
}
println(EnumTest.Q1)
println(EnumTest.CC)
}
}
2.语法介绍
Scala 没有从语言层面上支持 枚举,需要利用 继承的方式实现枚举。
object EnumTest extends Enumeration {
type EnumTest = Value //声明枚举对外暴露的变量类型
}
主要的思路就是 在 继承 Enumeration 的对象中 ,声明多个 Value 实例
1) 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)
2) 继承Value的时候,可以指定初始值,也就是起始下标
默认下标是 从0 开始。
object EnumTest extends Enumeration(10)
验证:
println(EnumTest.CC.id)
println(EnumTest.CC)
10
CC
3.扩展函数
我们有时候需要 一些扩展函数 ,帮助我们去处理,下面列举一些处理函数:
def checkExists(day: String): Boolean = this.values.exists(_.toString == day) //检测是否存在此枚举值
def showAll = this.values.foreach(println) // 打印所有的枚举值
println("if exists CC " + checkExists("CC"))
if exists CC true