Guo
Guo

Reputation: 1813

In Scala, how to abort the function?

In java, return can abort function:

public void f(int a){
    if(a < 0){
        return;    //return keywords can abort the function
    }
    //TODO:
}

how to abort the function in scala?

Upvotes: 0

Views: 595

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170899

In Scala, you just return from the function as normal:

def f(a: Int): Unit = { // Unit is Scala equivalent of void, except it's an actual type
  if (a < 0)
    () // the only value of type Unit
  else
    // TODO
}

You can use return () to make the early return more explicit, but this shouldn't normally be done. See e.g. https://tpolecat.github.io/2014/05/09/return.html.

Upvotes: 4

Related Questions