添加对 Scala 枚举进行操作的方法

Add methods that operate on Scala enums

假设我有一个枚举颜色,其中包含我的程序可能的颜色值:红色、蓝色和橙色。 然后我想添加适用于这些颜色的方法。如何在 Scala 中添加这些方法?

enum Color {
  case Red
  case Blue
  case Orange
}

我正在使用 Scala 版本 3。

我尝试制作一个 class,它将枚举类型 Color 的值作为参数,并包含枚举所需的方法。不过,我确实认为有更好的方法来处理这种情况。

您可以将方法直接添加到枚举中。

enum Color {
  case Red
  case Blue
  case Orange

  def colorToInt: Int = this match {
    case Red => ...
    case Blue => ...
    case Green => ...
  }

  // etc ...

}

或者,每个枚举案例都可以有自己的方法。根据您有多少枚举案例,以这种风格编写代码会更整洁。

enum Color {

  case Red extends Color {
    override def colorToInt: Int = ...
  }

  case Blue extends Color {
    override def colorToInt: Int = ...
  }

  case Orange extends Color {
    override def colorToInt: Int = ...
  }

  def colorToInt: Int // Note: abstract method
}

枚举和它们的 case 是 Scala 2 中已经存在的功能的有效语法糖,例如 case classes 和 sealed abstract classes。所以在概念上,你可以认为 enum 定义了一个完整的抽象 class,每个 case 定义了一个子 class。它们都可以有方法,案例从枚举继承方法,整个事情就像一个 OOP class 层次结构,因为它实际上 一个。

您可以阅读发生的确切翻译 on the original issue tracker for the feature。实际上,每个 case 都被编译为 case classval,具体取决于它是否需要任何自定义方法。