Tail recursion sumList

Hi,

I tried to do sumList as a tail recursion, but it doesn’t work for me.

import scala.annotation.tailrec

def sumList(ls: List[Int]): Int = {
if (ls.isEmpty) 0 else innerSum(ls,0)
}

@tailrec
def innerSum(ls: List[Int], acc: Int): Int ={
if (ls.isEmpty) acc
else innerSum(ls.tail,ls.head+acc)
}

I am getting the following error message!
could not optimize @tailrec annotaded method innersum it is neither private nor final

The error message states what is wrong. If you make your method private or final then it will be able to do the tail call optimisation.

quite often with tail recursive methods people will define it as such


def somefunc(whatever params) {
  @tailrec
  def doFunc(whatever params) {
     /// tail recursive method
  }

  doFunc(initial params)
}

then doFunc can’t be called from outside the someFunc method. and you don’t have to declare it private or final

1 Like

Oh I see thanks a lot. Why is it important to declare private or final?

The compiler needs to know that the method can’t be overriden by inheritance. I think the restriction doesn’t exist for methods declared on objects

1 Like

I see thanks a lot!!

A question related to sumList

def sumList(ls: List[Int]): Int = ls.foldRight(0){_ + _} //this works

def sumList(ls: List[Int]): Int = ls.head ::: ls.tail //I tried to do it with head and tail but it seems not working for the head says its an integer and is expecting a List. The head takes always the first element or not?

@tailrec only can use on a function inside a object or a final method in a class