aa8y
aa8y

Reputation: 3942

Why is the value not being returned as it should be here?

Why does this work?

object Foo extends App {
  def bar(s: String): String = {
    if (s.size == 0) "empty string"
    else if (s.size == 1) s + s
    else s.head + bar(s.tail)
  }

  println(bar(""))
  println(bar("s"))
  println(bar("soom"))
}

[info] Running example.Foo
empty string
ss
soomm

While this one doesn't.

object Foo extends App {
  def bar(s: String): String = {
    if (s.size == 0) "empty string"
    if (s.size == 1) s + s
    s.head + bar(s.tail)
  }

  println(bar(""))
  println(bar("s"))
  println(bar("soom"))
}

java.util.NoSuchElementException: next on empty iterator

Shouldn't the returns short-circuit the code and not go forward? I feel that there's a simple explanation to why the second code snippet is not working, but I can't seem to find out why.

Upvotes: 0

Views: 58

Answers (1)

Ryan Stull
Ryan Stull

Reputation: 1096

Firstly you're missing a return statement. In Scala the value on the last line of a function is returned as the return value.

Now your first code segement works because if else statements are treated as one expression and thus you do have an expression as the last line to return.

In your second code snippet the first two ifs have no effect because there's no return statement. They are evaluated then nothing happens. Your empty string case will make it to the s.head + bar(s.tail) line and the fail because .head cannot find an element.

You can either use your first code snippet or change your second one to this..

object Foo extends App {
  def bar(s: String): String = {
    if (s.size == 0) return "empty string"
    if (s.size == 1) return s + s
    s.head + bar(s.tail)
  }

  println(bar(""))
  println(bar("s"))
  println(bar("soom"))
}

Upvotes: 2

Related Questions