Wilson Ho
Wilson Ho

Reputation: 372

How to avoid return in scala

I have an example like this one:

def demo(a: Int, b: Int, c:Int): Int = {
        if (a == 1)
          return 10
        if (b == 2)
          return 20
        if (c == 3)
          return 30
        40
      }

The code works well, but I know in Scala we try to avoid the return. So I would like to ask there are any different way we can avoid the return? Thank you

Edited This is the real case I got, and I would like to avoid the return.

post("/") {

if (product_id <= 0)
    return BadRequest(Map("ERROR" -> "PRODUCT_ID IS WRONG"))

if (file_id.isEmpty())
    return BadRequest(Map("ERROR" -> "FILE ID NOT FOUND"))

if (data_type.isEmpty())
    return BadRequest(Map("ERROR" -> "FILE TYPE NOT FOUND"))

if (data_type.get != "cvs")
    return BadRequest(Map("ERROR" -> "FILE TYPE IS WRONG"))

OK(Map("SUCCESS" -> "THANK YOU"))
}

Upvotes: 1

Views: 213

Answers (2)

Liza Shakury
Liza Shakury

Reputation: 738

You can do something like that, for large number of parameters:

def demo(ints: Int*) =
  ints.foldLeft((0, 1, 40)) { (acc, i) =>
      if (acc._2 == i && acc._1 == 0) (1, acc._2, i * 10)
      else (acc._1, acc._2 + 1, acc._3)
    }._3

I am not sure it is easy to read, but if you have many arguments maybe it is something to consider. Some explanations: In the foldLeft we start with the (0, 1, 40) 0 is an indicator if we found value to return, 1 is an index in ints, and 40 is the result, if found another value to be returned it will be replaced. If "demo" is just a simple way to explain another problem you have, you should replace the condition and it's result according to your real problem.

Upvotes: 0

Assaf Mendelson
Assaf Mendelson

Reputation: 13001

The basic option would be to use if else:

if (a == 1) 10 else if (b == 2) 20 else if (c == 3) 30 else 40

Another option is to use pattern matching:

def demo(a: Int, b: Int, c: Int): Int = (a, b, c) match {
  case (1, _, _) => 10
  case (_, 2, _) => 20
  case (_, _, 3) => 30
  case _ => 40
}

Upvotes: 12

Related Questions