Enumeration应该算是程序语言里面比较通用的一个类型,在scala中也存在这样的类型, 我们看下Enumeration的定义:

abstract class Enumeration (initial: Int) extends Serializable

Enumeration是一个抽象类,它定义四个value方法,来设置内部的值, 四个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)

知道如何设置Enum的值后,我们就可以尝试创建一个Enum了。

println("Step 1: How to create an enumeration")
object Donut extends Enumeration {
type Donut = Value val Glazed = Value("Glazed")
val Strawberry = Value("Strawberry")
val Plain = Value("Plain")
val Vanilla = Value("Vanilla")
}

上面的例子中,我们创建了一个Enum,并且设置了几个值。

下面我们看下怎么取到Enum的值:

println("\nStep 2: How to print the String value of the enumeration")
println(s"Vanilla Donut string value = ${Donut.Vanilla}")

你可以看到如下的输出:


Step 2: How to print the String value of the enumeration
Vanilla Donut string value = Vanilla

下面是怎么输出Enum的id:

println("\nStep 3: How to print the id of the enumeration")
println(s"Vanilla Donut's id = ${Donut.Vanilla.id}")

结果如下:

Step 3: How to print the id of the enumeration
Vanilla Donut's id = 3

怎么输出所有的Enum项呢?

println("\nStep 4: How to print all the values listed in Enumeration")
println(s"Donut types = ${Donut.values}")

输出结果如下:

Step 4: How to print all the values listed in Enumeration
Donut types = Donut.ValueSet(Glazed, Strawberry, Plain, Vanilla)

接下来,我们看下怎么打印出所有的Enum:

println("\nStep 5: How to pattern match on enumeration values")
Donut.values.foreach {
case d if (d == Donut.Strawberry || d == Donut.Glazed) => println(s"Found favourite donut = $d")
case _ => None
}

输出如下:


Step 5: How to pattern match on enumeration values
Found favourite donut = Glazed
Found favourite donut = Strawberry

最后,我们看下怎么改变Enum值的顺序:

println("\nStep 6: How to change the default ordering of enumeration values")
object DonutTaste extends Enumeration{
type DonutTaste = Value val Tasty = Value(0, "Tasty")
val VeryTasty = Value(1, "Very Tasty")
val Ok = Value(-1, "Ok")
} println(s"Donut taste values = ${DonutTaste.values}")
println(s"Donut taste of OK id = ${DonutTaste.Ok.id}")

输出结果如下:


Step 6: How to change the default ordering of enumeration values
Donut taste values = DonutTaste.ValueSet(Ok, Tasty, Very Tasty)
Donut taste of OK id = -1

更多教程请参考 flydean的博客

Scala教程之:Enumeration的更多相关文章

  1. scala教程之:可见性规则

    文章目录 public Protected private scoped private 和 scoped protected 和java很类似,scala也有自己的可见性规则,不同的是scala只有 ...

  2. Scala教程之:深入理解协变和逆变

    文章目录 函数的参数和返回值 可变类型的变异 在之前的文章中我们简单的介绍过scala中的协变和逆变,我们使用+ 来表示协变类型:使用-表示逆变类型:非转化类型不需要添加标记. 假如我们定义一个cla ...

  3. Scala教程之:Either

    在之前的文章中我们提到了Option,scala中Option表示存在0或者1个元素,如果在处理异常的时候Option就会有很大的限制,因为Option如果返回None,那么我并不知道具体的异常到底是 ...

  4. Scala教程之:可变和不变集合

    文章目录 mutable HashMap immutable HashMap 集合在程序中是非常有用的,只有用好集合才能真正感受到该语言的魅力.在scala中集合主要在三个包里面:scala.coll ...

  5. Scala教程之:Future和Promise

    文章目录 定义返回Future的方法 阻塞方式获取Future的值 非阻塞方式获取Future的值 Future链 flatmap VS map Future.sequence() VS Future ...

  6. Scala教程之:PartialFunction

    Scala中有一个很有用的traits叫PartialFunction,我看了下别人的翻译叫做偏函数,但是我觉得部分函数更加确切. 那么PartialFunction是做什么用的呢?简单点说Parti ...

  7. Scala教程之:Option-Some-None

    文章目录 Option和Some Option和None Option和模式匹配 在java 8中,为了避免NullPointerException,引入了Option,在Scala中也有同样的用法. ...

  8. Scala教程之:scala的参数

    文章目录 默认参数值 命名参数 scala的参数有两大特点: 默认参数值 命名参数 默认参数值 在Scala中,可以给参数提供默认值,这样在调用的时候可以忽略这些具有默认值的参数. def log(m ...

  9. Scala教程之:可扩展的scala

    文章目录 隐式类 限制条件 字符串插值 s 字符串插值器 f 插值器 raw 插值器 自定义插值器 Scala是扩展的,Scala提供了一种独特的语言机制来实现这种功能: 隐式类: 允许给已有的类型添 ...

随机推荐

  1. win10配置易用命令行

    在 win10 下配置易用命令行 win10 相比 Linux 最大的短板之一是命令行. 这篇文章不会将 win10 配置到像Linux那样一行命令解决所有包的安装,只是从最大程度上方便开发. 我们主 ...

  2. STM32F103ZET6独立看门狗

    1.IWDG简介 STM32F103ZET6的独立看门狗(IWDG)是由内部LSI(内部约40KHZ低速时钟)时钟驱动的.由于IWDG是由内部低速时钟驱动,所以就算主时钟发生故障,IWDG依然能够工作 ...

  3. Visual Studio Code 1.44 设置简体中文界面语言(小白图文教程)

    作为一款微软出品的编辑器,安装完毕后,默认界面竟然不是中文!而更“丧心病狂”的是菜单里竟然连“设置”或“设置语言”这种PC软件常见选项也没有!!这种设计对小白而言简直 反!!!人!!!类!!! (默认 ...

  4. readthedocs网托管持多语言文档

    希望在readthedocs上创建支持多语言的文档,效果类似: 通过语言选项,可以切到到不同的语言版本:实现这个目标包含两个主要步骤: 在本地对文档进行翻译 在readthedocs.org上配置翻译 ...

  5. django_rest_framework视图传递参数给序列化器

    django_rest_framework视图传递参数给序列化器 视图中默认可以将request.data传递给序列化器,但request.data是不可更改的对象,但又想将额外的参数传递给序列化器 ...

  6. C++静态库和动态库

    静态库与动态库 首先简单介绍一下gcc 指令 ubuntu 下安装gcc g++ 方法 sudo apt install gcc g++ gcc 的简单使用 建立hello.c 源文件 gcc hel ...

  7. Python之 module安装

    如出现这种错误 ModuleNotFoundError: No module named 'numpy' 这种错误通常不会出现,因为Python的模块,通常在你安装Python shell的时候,就已 ...

  8. 使用spring连接mysql数据库出错

    最近在学习spring框架,但是在学到JdbcTemplate时连接数据库一直报错,百度谷歌各种查找都能没有解决问题,简直要癫狂,报错信息如下: org.springframework.jdbc.Ca ...

  9. Centos7_搭建暗网网站

    Tor运行原理 请求方需要使用:洋葱浏览器(Tor Browser)来对暗网网站进行访问 响应放需要使用:Tor协议的的Hidden_service 搭建步骤 更新YUM源: rpm -Uvh htt ...

  10. 【python实现卷积神经网络】激活层实现

    代码来源:https://github.com/eriklindernoren/ML-From-Scratch 卷积神经网络中卷积层Conv2D(带stride.padding)的具体实现:https ...