tags:

views:

104

answers:

3

I have an enumeration that I want to use in pattern matches in an actor. I'm not getting what i'd expect and, now, I'm suspecting I'm missing something simple.

My enumeration,

object Ops extends Enumeration {
  val Create = Value("create")
  val Delete = Value("delete")
}

Then, I create an Ops from a String:

val op = Ops.valueOf("create")

Inside my match, I have:

case (Ops.Create, ...)

But Ops.Create doesn't seem to equal ops.valueOf("create")

The former is just an atom 'create' and the later is Some(create)

Hopefully, this is enough info for someone to tell me what I'm missing...

Thanks

A: 

Enumeration.valueOf returns None or Some, because you may be asking to create a value that doesn't exist. In your case, for example, Ops.valueOf("blah") would return None, since you don't have an appropriate enumeration value.

To be honest, in this case, I'd use a case class or a case object instead of an Enumeration (they provide better type safety).

mipadi
A: 

It looks like I needed to use the 'get' method of the returned Some to actually get what I wanted. E.g.

ops.valueOf("create").get == Ops.Create

Seems neither intuitive nor friendly but it works.

williamstw
It's because `Enumeration.valueOf` returns an `Option` object, which means you have to use `get` to get the value value.
mipadi
+6  A: 

If you are just trying to get a copy of Create, then you should refer to it directly in your code:

val op = Ops.Create

But if you are parsing it from a string, the string might contain junk, so valueOf returns an Option:

val op1 = Ops.valueOf("create")  // Some(Ops.Create)
val op2 = Ops.valueOf("delete")  // Some(Ops.Delete)
val op3 = Ops.valueOf("aljeaw")  // None

Now, in your match you can just carry along the Option[Ops.Value] and look for:

case(Some(Ops.Create),...)

and you have built-in robustness to junk as input.

Rex Kerr
Ridiculously helpful response, thanks Rex!
williamstw