Frage

I am working on the Scala Coursera course right now (so I am still very new to the language and the paradigm).

In any case, I have completed the first lesson, but, when I run styleCheck against the code (which is also run as part of the grade), I receive warnings back that I should avoid using return. However, when I don't use return, my if statements just fall through. Here is an example of the code (no hints, per Coursera's honor policy):

  if(value == 0) return 1
  if(value == 1) return 0
  if(some.other.value.is.something) return 0

  recursiveCall(some, stuff)

Based on my understanding of the problem, I don't believe I can turn these into if/else's (I did try that, and then my solution wasn't correct). So, I'm stuck as to what possible options there may be. I'm also not understanding why I shouldn't use returns in the first place. Explanations/help on both would be much appreciated.

War es hilfreich?

Lösung

The return keyword exists in Scala, but you rarely need it.

The return value of a method in Scala is simply the value of the last expression in the method; you can leave out the return keyword.

Note that in Scala, if is an expression and not a statement - it evaluates to a value. For example, you can assign the result of an if expression to a variable:

val result = if (x == 3) 5 else 7

You could rewrite your code like this:

if (value == 0) 1
else if (value == 1) 0
else if (some.other.value.is.something) 0
else recursiveCall(some, stuff)

(assuming that recursiveCall(some, stuff) also returns a value).

Andere Tipps

Maybe the problem is about the recursion.

One sees this often:

def f(x: X, value: Value): Int = {
  def loop(x: X): Int = ???  // some recursive algorithm
  value match {
    case 0 => 1     // some guard conditions
    case 1 => 0
    case _ if some.condition => 0
    case _ => loop(x)
  }
}

That is, some local defs are followed by a small snippet that constitutes the small body of the function.

In particular, a local def is the recursive function to invoke.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top