Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala match/compare enumerations

Tags:

scala

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

like image 357
Tim Avatar asked May 05 '10 14:05

Tim


2 Answers

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.

like image 179
Rex Kerr Avatar answered Sep 27 '22 02:09

Rex Kerr


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).

like image 30
mipadi Avatar answered Sep 25 '22 02:09

mipadi