0

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?

Guo
  • 1,761
  • 2
  • 22
  • 45
  • 2
    Possible duplicate of [How do I break out of a loop in Scala?](http://stackoverflow.com/questions/2742719/how-do-i-break-out-of-a-loop-in-scala) – Ende Neu Jan 18 '16 at 13:52
  • 1
    You can still use `return` in Scala. Better would be to reorganize your code so it's not necessary though. – resueman Jan 18 '16 at 14:14

1 Answers1

4

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.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487