score:2

Accepted answer

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"))
}

Related Query

More Query from same tag