Does Scala have guards?

前端 未结 4 1380
旧时难觅i
旧时难觅i 2020-12-09 14:48

I started learning scala a few days ago and when learning it, I am comparing it with other functional programming languages like (Haskell, Erlang) which I had some familiari

4条回答
  •  無奈伤痛
    2020-12-09 15:17

    I stumbled to this post looking how to apply guards to matches with multiple arguments, it is not really intuitive, so I am adding an random example here.

    def func(x: Int, y: Int): String = (x, y) match {
      case (_, 0) | (0, _)  => "Zero"
      case (x, _) if x > -1 => "Positive number"
      case (_, y) if y <  0 => "Negative number"
      case (_, _) => "Could not classify"
    }
    
    println(func(10,-1))
    println(func(-10,1))
    println(func(-10,0))
    

提交回复
热议问题