Frage

I'm in my early scala hours and I expected the following two bits of code to behave the same but they do not. I was under the impression that "else" is optional.

Any ideas why? This is in a toString method (in a simple class representing rational numbers)

This works as expected, returns "1" (for 1/1):

if(numer == denom) {
  "1"
} else {
  numer + "/" + denom
}

This doesn't, returns "1/1":

if(numer == denom) {
  "1"
}

numer + "/" + denom
War es hilfreich?

Lösung

The else part is indeed optional, but the return value of a method is the value of the last expression in the method. So, when you don't put the else part in an actual else block, you always return that value. As a solution, you either use an if/else expression, which is the preferred way, or you use an actual return statement in the if statement.

// The return value of the method is the value of the if/else expression.
if (numer == denom) {
  "1"
} else {
  numer + "/" + denom
}

or

if (numer == denom) {
  return "1"
}

numer + "/" + denom
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top