开发者

Scala match/compare enumerations

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

T开发者_运维百科he 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


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.


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


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜