Scala: match on value

IF you want to match on a value in Scala you can do so simply. Here, I’m using it to handle commands from RabbitMQ in this format:

index,garysieling.com
update,garysieling.com,12345

Here is the code:

val items = message.split(",")
val command = items(0);

command match {
  case "index" => {
    val domain = items(1)
    ...
  }
  case "update" => {
    val id = items(1)
    val domain = items(2)

    ...
  }
}

You can also just match on the array itself. The nice thing about this is you can have the different match entries be of different length. Unfortunately you have to write “Array” on each line – if you leave these off they are treated like a Tuple, which is not the output of split:

case Array("index", domain: String) => {
...
}
case Array("update", id: String, arg: String) => {
}

You can also leave off the type definitions (I put these in to start so I could get it to compile). You can also remove the brackets if the right hand side is one expression:
case Array(“index”, domain) => …
case Array(“update”, id, arg) => …

Leave a Reply

Your email address will not be published. Required fields are marked *