Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing enum parameter to a case class does not work

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

like image 930
user21845 Avatar asked May 10 '10 18:05

user21845


1 Answers

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)
}
like image 53
Michel Krämer Avatar answered Nov 04 '22 21:11

Michel Krämer