views:

65

answers:

1

Can 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

+7  A: 

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)
}
Michel Krämer
Great I new there was a way!