如何在类中使用Scala枚举。
如何在类中使用Scala枚举。
我正在学习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的警告:
类\'Car\'必须声明为抽象或在\'Car\'中实现抽象成员\'typed: Car.this.CarType.CarType\'
我不确定为什么它想要我实现变量,而且该类并不打算是抽象的。我想要类似于Java中使用枚举。
admin 更改状态以发布 2023年5月21日
你要找的是一个Scala Case Class。
class Car(maxSpeed: Integer) case class Minivan(maxSpeed: Integer) extends Car(maxSpeed: Integer) case class Hodrod(maxSpeed: Integer) extends Car(maxSpeed: Integer) case class Coupe(maxSpeed: Integer) extends Car(maxSpeed: Integer)
在Scala中,Java中存在的枚举并不常用。通过像上面那样的结构,您可以利用Scala强大的模式匹配来执行以下操作:
val unknownCar = getCar() // Some function that gets a car unknownCar match { case Minivan => println("Driving the kids") case Hodrod => println("Tearing up the drag") case Coupe => println("Riding low") }
…同时仍然可以将其视为 Car
。
由于它们是案例类,所以Scala有很多东西可以帮助您。
请注意Enumeration的文档:
通常这些值枚举某物可以采取的所有可能形式,并提供了与案例类相比更轻量级的替代方案。
只有当您不打算将这些值用于其他任何用途时,才应该真正使用它-但即使在那里,案例类通常也会为您提供更好的服务。
把枚举移到类的外部:\n
// Enums object CarType extends Enumeration { type CarType = Value val PERIPHERAL, COMPUTER, EMPTY = Value } class Car(maxSpeed: Integer) { import CarType._ // Fields val repeated: CarType }
\n或者把它移到伴生对象中:\n
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 } }
\n问题在于类内部定义的东西仅在该类的实例范围内(不同于某些其他语言)。\n尽管如此,我建议使用代数数据类型而不是枚举:\n
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)
\n关于封闭特质的更多信息,请参见这个SO问答。