Scala_Scala类 =》 枚举类

 

       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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值