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. Aho-Corasick automaton

    目录 KMP 算法 BF 算法 KMP 算法 避免重复遍历 算法思想 代码实现 匹配函数 求 next 数组 字典树 多模匹配 构造字典树 字典树的结构体定义 构造算法 伪代码 代码实现 失配指针 功 ...

  2. P1345 [USACO5.4]奶牛的电信(点拆边 + 网络最小割)

    题目描述 农夫约翰的奶牛们喜欢通过电邮保持联系,于是她们建立了一个奶牛电脑网络,以便互相交流.这些机器用如下的方式发送电邮:如果存在一个由c台电脑组成的序列a1,a2,-,a©,且a1与a2相连,a2 ...

  3. 吐槽,Java 设计的槽点

    今天不灌水,直接上干货!希望下面的讲解,能与你产生一些共鸣. 1. 求长度各有千秋 你是否曾经在面试的时候,经常被问到:数组有没有 length() 方法?字符串有没有 length() 方法? 集合 ...

  4. JavaScript-原始值和引用值

    一.原始值和引用值的概念 在 ECMAScript 中,变量可以存在两种类型的值,即原始值和引用值. 1.1 原始值 (1)原始值指的是 原始类型 的值,也叫 基本类型,例如 Number.Stirn ...

  5. 命令行工具nslookup查域名DNS服务器

    在使用的操作系统里进入终端, 1.输入 nslookup 回车 2.输入 set type=ns 回车 3.输入域名(不带WWW的),如:baidu.com 回车 操作过程如下, > set t ...

  6. 手动搭建I/O网络通信框架3:NIO编程模型,升级改造聊天室

    第一章:手动搭建I/O网络通信框架1:Socket和ServerSocket入门实战,实现单聊 第二章:手动搭建I/O网络通信框架2:BIO编程模型实现群聊 在第二章中用BIO编程模型,简单的实现了一 ...

  7. Loop Unrolling 循环展开

    在csapp第五章5.2中提到了循环展开(loop unrolling).这里展开一下为什么循环展开可以提升程序的效率. 以书中计算数组和的两段代码为例: 1.未展开: void psum1(floa ...

  8. JavaScript 入门 (一)

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  9. Linux 文件管理篇(一 档案读写)

    由第一行开始显示文件内容        cat 由最后一行开始显示文件内容        tac 一页一页的显示文件内容            more 一页一页的显示文件内容(可以向前翻页)     ...

  10. MySQL学习之路6-数据表连接方式

    内连接 关键字: inner join  on 语句:select * from <a_table> inner join <b_table> on a.id = b.id ; ...