Enumeration

While enumerations are a built-in part of many programming languages, Scala takes a different route and implements them as an Enumeration class in its standard library.
You just define an object that extends the Enumeration class and follow its idioms. So, at the byte code level, there is no connection between Scala enumerations and the enum constructs in Java.

package com.brown


/**
  * Created by BrownWong on 2016/9/29.
  */

object Hello {

  def main(args: Array[String]): Unit = {
    println("ID\tBreed")
    for (breed <- Breed.values) println(s"${breed.id}\t$breed")
  }

}

object Breed extends Enumeration {
  type Breed = Value
  val doberman = Value("Doberman Pinscher")
  val yorkie = Value("Yorkshire Terrier")
  val scottie = Value("Scottish Terrier")
  val dane = Value("Great Dane")
  val portie = Value("Portuguese Water Dog")
}

output

ID  Breed
0   Doberman Pinscher
1   Yorkshire Terrier
2   Scottish Terrier
3   Great Dane
4   Portuguese Water Dog

There are other overloaded versions of the Value method. We’re using the one that takes a String. Another one takes no arguments, so the string will just be the name of the value.
Here is the second example:

package com.brown


/**
  * Created by BrownWong on 2016/9/29.
  */

object Hello {

  import WeekDay._

  def main(args: Array[String]): Unit = {
    WeekDay.values filter isWorkingDay foreach println
  }

  def isWorkingDay(d: WeekDay) = !(d == Sat || d == Sun)
}

object WeekDay extends Enumeration {
  type WeekDay = Value
  val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}

output

Mon
Tue
Wed
Thu
Fri

You don’t actually see enumerations used a lot in Scala code, especially compared to Java code. They are lightweight, but they are also limited to the case where you know in advance the exact set of values to define. Clients can’t add more values.

Instead, case classes are often used when an “enumeration of values” is needed. They are a bit more heavyweight, but they have two advantages:

  1. First, they offer greater flexibility to add methods and fields, and to use pattern matching on them.
  2. The second advantage is that they aren’t limited to a fixed set of known values. Client code can add more case classes to a base set that your library defines, when useful.


Ref

《Programming Scala》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值