Scala: "explicit return" required?

263 views Asked by At

I thought in Scala I don't need to explicit put "return" in the return statement. So I have the following code:

  def checkSimple(str1: String, str2: String): Boolean = {

    if (str1 > str2) {
      println("str1 > str2")
      true
    }

    println("str1 <= str2")
    false
  }

if I ran my above code with checkSimple("200", "150"), I got wrong result below:

str1 > str2
str1 <= str2

But if I add "return" in front of "true" like below, everything works correctly:

  def checkSimple(str1: String, str2: String): Boolean = {

    if (str1 > str2) {
      println("str1 > str2")
      return true
    }

    println("str1 <= str2")
    false
  }

So is "return" actually required in the return statement line?

Thanks!

1

There are 1 answers

0
Angelo Genovese On BEST ANSWER

The last expression's value is used as the return so:

  def checkSimple(str1: String, str2: String): Boolean = {
    if (str1 > str2) {
      println("str1 > str2")
      true
    } else {
      println("str1 <= str2")
      false
    }
  }

will behave the way you expect