gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:49:00 25 4
gpt4 key购买 nike

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

enum Color {
case Red
case Blue
case Orange
}

我正在使用 Scala 版本 3。

我尝试制作一个类,该类将枚举类型 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
}

枚举和它们的案例是 Scala 2 中已经存在的功能的有效语法糖,例如案例类和密封抽象类。所以从概念上讲,您可以将 enum 视为定义一个完整的抽象类,而将每个 case 视为定义一个子类。它们都可以有方法,案例从枚举继承方法,整个事情就像 OOP 类层次结构一样工作,因为它实际上一个。

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

关于scala - 添加对 Scala 枚举进行操作的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70550389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com