Match “fallthrough”: executing same piece of code for more than one case?

前端 未结 4 899
死守一世寂寞
死守一世寂寞 2020-12-17 07:38

What is the Scala\'s way to write the following code:

 int i;

 switch(i) {
   case 1:  
         a();
         break;

   case 2:
   case 15:
        b();
          


        
4条回答
  •  情书的邮戳
    2020-12-17 08:14

    While not applicable here, for more complex problems you can 'fallthrough' in a sense using the andThen function on partial functions.

     def do_function_a() { println("a"); }
     def do_function_b() { println("b"); }
     val run_function:PartialFunction[String, String] = { 
           case "a" => do_function_a(); "b"
           case "b" => do_function_b(); "c"
     }
    
     (run_function andThen run_function)("a") // a\nb
    

提交回复
热议问题