0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[メモ] Scala の OpenEnum を使った

Last updated at Posted at 2025-01-09

使い方

以下のように定義できる。

sealed trait Fruit

object Fruit extends AEnum[Fruit] {
  case object Apple extends Fruit
  case object Banana extends Fruit
  case object Orange extends Fruit

  implicit lazy val jsfmt: JsFormat[OpenEnum[Fruit]] = JsFormat.enum(enumNames)
  implicit lazy val schema: Schema[OpenEnum[Fruit]] = Schema.enum(enumNames).named("Fruit")
  implicit lazy val arbitrary = Deriving[Arbitrary[Fruit]]
  implicit lazy val openEnumArbitrary: Arbitrary[OpenEnum[Fruit]] = Deriving[Arbitrary[OpenEnum[Fruit]]]

  def enumNames: EnumNames[OpenEnum[Fruit]] = OpenEnum.enumNames(source)
  override def namedValues: List[Enum.NamedValue[Fruit]] = Enum.values[Fruit]
}

OpenEnum[Fruite]]型のオブジェクトは以下のように初期化することができる。(地味に詰まった。)

val apple: OpenEnum[Fruit] = OpenEnum(Fruit.Apple)

また、enumの名前をStringで取り出す方法は以下。

Fruit.Apple.toString // "Apple"

Ref.

image.png

image.png

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?