Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

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")



Attender(Hidehito Nozawa,Maybe)
Attender(Hidehito Nozawa,Going)
Attender(Hidehito Nozawa,NotGoing)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
Help us understand the problem. What are the problem?