LoginSignup
48
43

More than 5 years have passed since last update.

Scalaで列挙型(enum)を作る

Posted at

ScalaのEnumerationは使うな - Scalaで列挙型を定義するには | Scala Cookbookによると、Scalaで列挙型を定義するには Enumeration よりも case object を使ったほうが便利とのこと。

例: 出欠状況の列挙型の例

// 列挙型をcase objectと継承を使って定義
sealed abstract class AttendingStatus
case object Going extends AttendingStatus
case object NotGoing extends AttendingStatus
case object Maybe extends AttendingStatus

var attendingStatus: AttendingStatus = Going

// case object だとマッチャーが使えて便利
attendingStatus match {
    case Going => println("出席")
    case NotGoing => println("欠席")
    case Maybe => println("未定")
}

出欠状況の選択肢を GoingNotGoingMaybe の3種類だけに限定するために、下記の工夫をする。
* sealed は同一ファイル内でのみ継承が可能にする。つまり、どこかで勝手に選択肢追加されることを防ぐ目的。
* abstractAttendingStatus 自体が選択肢のひとつになることを防ぐ目的。
* case class ではなく case object にしているのは勝手な継承をさせないため。 (sealedだけではサブクラスの継承を防げない)

実際のコードでは、列挙型を使うクラスのコンパニオンオブジェクトの一部にしたほうが、整理されていていいと思う。

// Attenderエンティティ
case class Attender(name: String, status: Attender.Status = Attender.Status.Maybe) {
    def attend = copy(status = Attender.Status.Going)
    def absent = copy(status = Attender.Status.NotGoing)
}

object Attender {
    // 列挙型の定義はここ
    sealed abstract class Status
    object Status {
        case object Going extends Status
        case object NotGoing extends Status
        case object Maybe extends Status
    }
}

val attender = Attender("Hidehito Nozawa")

println(attender)
println(attender.attend)
println(attender.absent)

実行結果

Attender(Hidehito Nozawa,Maybe)
Attender(Hidehito Nozawa,Going)
Attender(Hidehito Nozawa,NotGoing)
48
43
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
48
43