开发者

Passing enum parameter to a case class does not work

开发者 https://www.devze.com 2022-12-29 15:59 出处:网络
C开发者_运维知识库an someone tell me why this does not work? case class XY(enum: MyEnum) object MyEnum extends Enumeration {

C开发者_运维知识库an someone tell me why this does not work?

case class XY(enum: MyEnum)

object MyEnum extends Enumeration {
  val OP1, OP2 = Value 
}

Error: not found: type MyEnum


This is because MyEnum is an object and objects are singletons. It's not possible to pass singletons as arguments to case classes, because that would impose there is more than one instance of this object.

If you want to pass a value of MyEnum (i.e. an enumeration value) use MyEnum.Value:

case class XY(enum: MyEnum.Value)

object MyEnum extends Enumeration { val OP1, OP2 = Value }

After that you can use MyEnum as expected:

val x = XY(MyEnum.OP1)

By the way: A common pattern is to define a type alias, so you can tweak the code a little bit (i.e. use MyEnum instead of MyEnum.Value and OP1 instead of MyEnum.OP1):

object MyEnum extends Enumeration {
  type MyEnum = Value
  val OP1, OP2 = Value
}

import MyEnum._

case class XY(enum: MyEnum)

class C {
  val x = XY(OP1)
}
0

精彩评论

暂无评论...
验证码 换一张
取 消