tags:

views:

6

answers:

1

Hi,

I have an Enumeration class, and have extracted "id" values from some of the members and stored them in Int variables. Whether that was a good idea/not is not the question.

What the question is, is why I cant seem to do the following:

Let's say I have s : Int which holds one of these id values ... and I would like to do matching against the actual enumeration values. Something like the following:

s match { QID.MEM_RD.id => // something

QID.MEM_WRT.id => // something else }

This seems to give me a failure that "stable identifier is required". So I end up writing code like

if (s == QID.MEM_RD.id) // something else if (s == QID.MEM_WRT.ID) // something else

So .. it's just kind of odd to me that Scala has this nice feature, but appears to force me to go back to an uglier style of coding --- when I would much rather use their match feature.

Any ideas? I guess I can restructure to stop extracting ids ... but it's just the idea that match doesn't allow this that irks me a bit.

(Note: I don't try to store the id values anywhere persistently ... just use them for the duration of program execution.)

-Jay

A: 

I think you can use if guards in that case.

s match {
  case a if (s == QID.MEM_RD.id) => println("you read!")
  case b if (s == QID.MEM_WRT.id) => println("you wrote!")
}

http://programming-scala.labs.oreilly.com/ch03.html#PatternMatching

Davide Inglima