Ahmad Al-Kurdi
Ahmad Al-Kurdi

Reputation: 2305

How to match the matched case as well as another below cases?

I know that I can not use break in the Scala match statement.

Is there a why to match the matched case as well as some below cases?

For example in Java I can do the following :

int i=3;
switch(i) {
    case 1:
        a();
        break;
    case 2:
        b();
    case 3:
        c();
    case 4:
        d();
        break;
    default: z();
}

How I can do the same thing on the Scala?

Upvotes: 1

Views: 1036

Answers (3)

igorpcholkin
igorpcholkin

Reputation: 967

You can't translate your Java code directly to Scala without code duplication as you can't execute several alternatives in match statement in a single pass. What you can do however to avoid code duplication in alternatives is to process the same match statement multiple times,

for example

@tailrec
def switch(x : Int): Unit =
     x match {
       case 1 => a()
       case 2 => b(); switch(3)
       case 3 => c(); switch(4)
       case 4 => c()
       case _ => z()
     }

switch(3)

Upvotes: 0

jwvh
jwvh

Reputation: 51271

It can be done, but you have to define your own switch method.

// switch statement with dropthrough logic
def switch[T](i: T)(actions: (T, () => Unit)*)(default: => Unit) = {
  val acts = actions.dropWhile(_._1 != i).map{_._2}
  if (acts.isEmpty) default
  else acts.foreach{_()}
}

This works, but it has a slightly unorthodox syntax. And because it requires a return, instead of break, there should be no code that follows this switch.

def someMethod(i:Int): Unit =
  switch(i)(
    1 -> {() => println("do 1"); return}, // return instead of break
    2 -> {() => println("do 2")},
    3 -> {() => println("do 3")},
    4 -> {() => println("do 4")}  // no comma after final case
  )(default = println("do default"))

All in all, likely to be more hassle than it's worth.

Upvotes: 2

Shaido
Shaido

Reputation: 28367

You will need to write the code twice (or more). In Scala it is not possible to fall through from one case to the next. Even in languages where it is possible, it is generally not a good idea; it can be a source of hard-to-find bugs (although there are situations where it can be used effectively).

In Scala the code would look like this:

val i = 3
i match {
  case 1 => a()
  case 2 => {
    b()
    c()
    d()
  }
  case 3 => {
    c()
    d()
  }
  case 4 => d()
  case _ => z()

Upvotes: 3

Related Questions