Daniel Moore Daniel Moore - 25 days ago 13
Scala Question

How to break out of or exit a void method in Scala?

This is a very basic question, but I can't seem to find the answer anywhere. In a Scala method with no return value, how can I exit the method prematurely?

For example,

def printPositiveNumbersSum (n1: Int, n2: Int) = {
if (n1 < 0 || n2 < 0)
// How do I break out of this method here?
println(n1 + n2)
}


Attempting to use
return
like in Java raises an error that
printPositiveNumbersSum
doesn't have a return type.

I know that I could just make this an if-else statement, but if there are multiple conditions under which I'd like to exit the method and return to its caller, this becomes unwieldy quickly.

Answer

Basic questions have a habit of being more interesting than they look. There are a couple of ways to approach this which are possibly worth considering as alternatives. The foundation though, is that everything returns a value of a certain type, and the compiler tries to figure out what that type is. In your case printPostiveNumbersSum returns something of a certain type.

  • Let your method return a unit. The type Unit means a function, or piece of executable code. This answer has already been mentioned.
  • Consider returning an Option[Int] for the sum. If the validation succeeds, you return Some(sum) and if it fails you return None. The caller can then decide what to do in the case of failure, perhaps using a match { case Some(sum)... construct.

    def positiveNumbersSum (n1: Int, n2: Int): Option[Int] = {
      if (n1 < 0 || n2 < 0)
        None
      else Some(n1 + n2)
    }
    
  • But in more complex cases, when you may have more rules to consider, it can be handy to return the reason for the failure rather than just returning a None. In this case, I find Either handy. You get to specify two return types. Again, the caller can differentiate with a match { case Left(reason)... case Right(sum)... construct.

    def positiveNumbersSum (n1: Int, n2: Int): Either[String,Int] = {
      if (n1 < 0 || n2 < 0)
        Left("One of the numbers is negative")
      else Right(n1 + n2)
    }