Scala - case match partial string

jhukdev picture jhukdev · Mar 19, 2012 · Viewed 35.2k times · Source

I have the following:

serv match {

    case "chat" => Chat_Server ! Relay_Message(serv)
    case _ => null

}

The problem is that sometimes I also pass an additional param on the end of the serv string, so:

var serv = "chat.message"

Is there a way I can match a part of the string so it still gets sent to Chat_Server?

Thanks for any help, much appreciated :)

Answer

Kyle picture Kyle · Mar 19, 2012

Have the pattern matching bind to a variable and use a guard to ensure the variable begins with "chat"

// msg is bound with the variable serv
serv match {
  case msg if msg.startsWith("chat") => Chat_Server ! Relay_Message(msg)
  case _ => null
}