scala - 如何在类中使用 Scala 枚举

标签 scala enums

我正在学习 Scala,并尝试为项目获取简单的枚举设置。我检查了一些示例,但似乎没有一个适合,Scala 文档和 StackOverflow 上的所有示例都是针对对象内的枚举,而不是类。我收到一条我不明白的 IDE 警告。我是从 Java 初学者开始接触 Scala,这可能是我感到困惑的原因。

代码如下:

class Car(maxSpeed: Integer) {

  // Enums
  object CarType extends Enumeration {
    type CarType = Value
    val PERIPHERAL, COMPUTER, EMPTY = Value
  }
  import CarType._

  // Fields
   val repeated: CarType
}

当我将鼠标悬停在类名称上时,我可以看到此 Intellij 警告:

Class 'Car' must either be declared abstract or implement abstract member 'typed: Car.this.CarType.CarType' in 'Car'

我不确定为什么它要我实现我的变量,并且该类并不是抽象的。我想像在 Java 中使用枚举一样使用枚举。

最佳答案

将枚举移到类之外:

// Enums
object CarType extends Enumeration {
  type CarType = Value
  val PERIPHERAL, COMPUTER, EMPTY = Value
}
class Car(maxSpeed: Integer) {
  import CarType._

  // Fields
   val repeated: CarType
}

或者将其移至companion对象:

class Car(maxSpeed: Integer) {
  import Car.CarType._

  // Fields
   val repeated: CarType
}

object Car {
  object CarType extends Enumeration {
    type CarType = Value
    val PERIPHERAL, COMPUTER, EMPTY = Value
  }
}

问题在于,类内部定义的内容的范围仅限于该类的实例(与其他一些语言不同)。

也就是说,我建议使用代数数据类型而不是枚举:

sealed trait CarType
object CarType {
  case object Peripheral extends CarType // strange choice of names
  case object Computer extends CarType
  case object Empty extends CarType
}

case class Car(maxSpeed: Int, carType: CarType)

有关密封特征的更多信息,请参阅 this所以问答

关于scala - 如何在类中使用 Scala 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39402181/

相关文章:

sql - 如何在 Redshift 中创建枚举?

struct - Swift - 访问结构

kotlin - 使用 kotlin 枚举避免 when 表达式中出现 else 语句

scala - Scala 中带有隐式参数的函数类型

scala - 在 akka 消息中保留类型/类标签

json - Spark 默认空列数据集

http - 如何在 Spray 框架中获取传入 IP 地址

c++ - 如何在不属于家庭的类(class)之间共享枚举?

scala - Gatling-scala 检查 2 个状态代码(或)

postgresql - SQL查询以获取枚举可以具有的所有值