-1

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!

2
  • How is the compiler supposed to know your intent was to return true in the if statement? Jun 10, 2015 at 19:48
  • Sometimes -Xlint will warn about such mistakes. But FSR it doesn't even warn about def g(i: Int, j: Int) = { if (i < j) true ; false }. It warns on def f = { true ; false }
    – som-snytt
    Jun 11, 2015 at 4:43

1 Answer 1

7

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.