Recursive call not in tail position

Let's say I define the following function:

final def myFunc[T](list: List[T]): List[T] = list match {
        case h :: t =>
            h :: myFunc(t)
        case _ =>
            Nil
    } 

When I add tailrec annotation, the compiler gives me the following error:

failed to optimize @tailrec annotated myFunc method: it contains a recursive call not in tail position: ^ Nil.

I am confused by how a Nil declaration can be a recursive call?

+4
source share
1 answer

The problem is not with Nil, but with h :: myFunc(t), because it is myFunc(t)not the last call. The last call is made by the operator ::according to the result myFunc(t). This is why a function is not tail recursive.

+6
source

All Articles