Scala3 枚举语法的最终版本是什么?
What's the final version of Scala3's enum syntax?
我想重写枚举 class 中的方法,如 Add enum construct
中提到的以下示例
enum class Option[+T] extends Serializable {
def isDefined: Boolean
}
object Option {
def apply[T](x: T) = if (x != null) Some(x) else None
case Some[+T](x: T) {
def isDefined = true
}
case None {
def isDefined = false
}
}
但是,代码无法在 Scala 3.0 中编译。
如何更改代码以使其工作?谢谢。
编辑感谢@Mario Galic 的回答。
我想把一系列的压缩方法归为一个枚举,如下:
enum CompressionMethod:
def compress(out: OutputStream): OutputStream
def decompress(in: InputStream): InputStream
case GZIP extends CompressionMethod: ...
case BZIP extends CompressionMethod: ...
case NONE extends CompressionMethod: ...
如果我将所有实现打包为:
enum CompressionMethod:
def compress(out: OutputStream): OutputStream = this match
case NONE => out
case BZIP => a lot codes ..
case GZIP => a lot codes ..
case ...
此外,如果我稍后添加另一个案例,而不只是添加另一个 case instance
本身,我需要修改 compress
方法。类似于:
enum CompressionMethod:
def compress(out: OutputStream): OutputStream
case GZIP extends CompressionMethod:
override def compress(out: OutputStream): OutputStream =
...
case BZIP extends CompressionMethod:
override def compress(out: OutputStream): OutputStream =
...
一个技巧是检查最新用法的测试,例如,tests/run/enum-Option1.scala
$ scala3-repl
scala> enum Option1[+T]:
| case Some1(x: T)
| case None1
|
| def isDefined: Boolean = this match
| case None1 => false
| case _ => true
|
// defined class Option1
scala> import Option1.*
scala> Some1(42).isDefined
val res0: Boolean = true
scala> None1.isDefined
val res1: Boolean = false
我想重写枚举 class 中的方法,如 Add enum construct
中提到的以下示例enum class Option[+T] extends Serializable {
def isDefined: Boolean
}
object Option {
def apply[T](x: T) = if (x != null) Some(x) else None
case Some[+T](x: T) {
def isDefined = true
}
case None {
def isDefined = false
}
}
但是,代码无法在 Scala 3.0 中编译。 如何更改代码以使其工作?谢谢。
编辑感谢@Mario Galic 的回答。
我想把一系列的压缩方法归为一个枚举,如下:
enum CompressionMethod:
def compress(out: OutputStream): OutputStream
def decompress(in: InputStream): InputStream
case GZIP extends CompressionMethod: ...
case BZIP extends CompressionMethod: ...
case NONE extends CompressionMethod: ...
如果我将所有实现打包为:
enum CompressionMethod:
def compress(out: OutputStream): OutputStream = this match
case NONE => out
case BZIP => a lot codes ..
case GZIP => a lot codes ..
case ...
此外,如果我稍后添加另一个案例,而不只是添加另一个 case instance
本身,我需要修改 compress
方法。类似于:
enum CompressionMethod:
def compress(out: OutputStream): OutputStream
case GZIP extends CompressionMethod:
override def compress(out: OutputStream): OutputStream =
...
case BZIP extends CompressionMethod:
override def compress(out: OutputStream): OutputStream =
...
一个技巧是检查最新用法的测试,例如,tests/run/enum-Option1.scala
$ scala3-repl
scala> enum Option1[+T]:
| case Some1(x: T)
| case None1
|
| def isDefined: Boolean = this match
| case None1 => false
| case _ => true
|
// defined class Option1
scala> import Option1.*
scala> Some1(42).isDefined
val res0: Boolean = true
scala> None1.isDefined
val res1: Boolean = false