Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign name to intermediate whilst pattern matching in Scala

Tags:

scala

I'm doing some pattern matching on a colon delimited String as follows:

case s:String => s.split(":") match {
  case Array("foo","bar") => ...
  case Array("hello",_,_) => ...
  ...
}

How can I rearrange the code to assign a name to the array returned by s.split(":")?

I've tried the following to no avail:

case s:String => val x = s.split(":") match {
  case Array("foo","bar") => // try to use x here
  ...
}
like image 481
Michael Avatar asked Jul 18 '12 12:07

Michael


Video Answer


1 Answers

case s:String => s.split(":") match {
  case x @ Array("foo","bar") => ...
  case x @ Array("hello",_,_) => ...
  ...
}

Or

case s:String =>
  val x = s.split(":")
  x match {
    case Array("foo","bar") => ...
    case Array("hello",_,_) => ...
    case Array(aStr, "bar") => println(aStr.toUpperCase)
    ...
}
like image 131
Malte Schwerhoff Avatar answered Sep 20 '22 13:09

Malte Schwerhoff