在 Scala 中返回

我是一个新手 Scala 程序员,遇到了一个奇怪的行为。

def balanceMain(elem: List[Char]): Boolean =
{
if (elem.isEmpty)
if (count == 0)
true;
else false;


if (elem.head == '(')
balanceMain(elem.tail, open, count + 1);....

如果 elem.isEmptycount == 0,基本上我想返回 true。否则,我想返回 false。

现在上面我已经读到,没有必要在 scala 中添加 return 语句。所以我省略了上面的 return。但它不返回布尔值。如果我添加返回语句作为 return true。效果非常好。为什么会这样?

另外,为什么在 scala 中使用 return 语句被认为是一种不好的做法

131279 次浏览

I don't program Scala, but I use another language with implicit returns (Ruby). You have code after your if (elem.isEmpty) block -- the last line of code is what's returned, which is why you're not getting what you're expecting.

EDIT: Here's a simpler way to write your function too. Just use the boolean value of isEmpty and count to return true or false automatically:

def balanceMain(elem: List[Char]): Boolean =
{
elem.isEmpty && count == 0
}

It's not as simple as just omitting the return keyword. In Scala, if there is no return then the last expression is taken to be the return value. So, if the last expression is what you want to return, then you can omit the return keyword. But if what you want to return is not the last expression, then Scala will not know that you wanted to return it.

An example:

def f() = {
if (something)
"A"
else
"B"
}

Here the last expression of the function f is an if/else expression that evaluates to a String. Since there is no explicit return marked, Scala will infer that you wanted to return the result of this if/else expression: a String.

Now, if we add something after the if/else expression:

def f() = {
if (something)
"A"
else
"B"


if (somethingElse)
1
else
2
}

Now the last expression is an if/else expression that evaluates to an Int. So the return type of f will be Int. If we really wanted it to return the String, then we're in trouble because Scala has no idea that that's what we intended. Thus, we have to fix it by either storing the String to a variable and returning it after the second if/else expression, or by changing the order so that the String part happens last.

Finally, we can avoid the return keyword even with a nested if-else expression like yours:

def f() = {
if(somethingFirst) {
if (something)      // Last expression of `if` returns a String
"A"
else
"B"
}
else {
if (somethingElse)
1
else
2


"C"                // Last expression of `else` returns a String
}

}

By default the last expression of a function will be returned. In your example there is another expression after the point, where you want your return value. If you want to return anything prior to your last expression, you still have to use return.

You could modify your example like this, to return a Boolean from the first part

def balanceMain(elem: List[Char]): Boolean = {
if (elem.isEmpty) {
// == is a Boolean resulting function as well, so your can write it this way
count == 0
} else {
// keep the rest in this block, the last value will be returned as well
if (elem.head == "(") {
balanceMain(elem.tail, open, count + 1)
}
// some more statements
...
// just don't forget your Boolean in the end
someBoolExpression
}
}

Don't write if statements without a corresponding else. Once you add the else to your fragment you'll see that your true and false are in fact the last expressions of the function.

def balanceMain(elem: List[Char]): Boolean =
{
if (elem.isEmpty)
if (count == 0)
true
else
false
else
if (elem.head == '(')
balanceMain(elem.tail, open, count + 1)
else....

This topic is actually a little more complicated as described in the answers so far. This blogpost by Rob Norris explains it in more detail and gives examples on when using return will actually break your code (or at least have non-obvious effects).

At this point let me just quote the essence of the post. The most important statement is right in the beginning. Print this as a poster and put it to your wall :-)

The return keyword is not “optional” or “inferred”; it changes the meaning of your program, and you should never use it.

It gives one example, where it actually breaks something, when you inline a function

// Inline add and addR
def sum(ns: Int*): Int = ns.foldLeft(0)((n, m) => n + m) // inlined add


scala> sum(33, 42, 99)
res2: Int = 174 // alright


def sumR(ns: Int*): Int = ns.foldLeft(0)((n, m) => return n + m) // inlined addR


scala> sumR(33, 42, 99)
res3: Int = 33 // um.

because

A return expression, when evaluated, abandons the current computation and returns to the caller of the method in which return appears.

This is only one of the examples given in the linked post and it's the easiest to understand. There're more and I highly encourage you, to go there, read and understand.

When you come from imperative languages like Java, this might seem odd at first, but once you get used to this style it will make sense. Let me close with another quote:

If you find yourself in a situation where you think you want to return early, you need to re-think the way you have defined your computation.

Use case match for early return purpose. It will force you to declare all return branches explicitly, preventing the careless mistake of forgetting to write return somewhere.