user79074
user79074

Reputation: 5270

Recursive call not in tail position

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 a tailrec annotation the compiler gives me the following error:

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

I am confused as to how the declaration of Nil can be a recursive call?

Upvotes: 8

Views: 1149

Answers (1)

Gregor Raýman
Gregor Raýman

Reputation: 3081

The problem is not with the Nil but with h :: myFunc(t) because myFunc(t) is not the last call. The last call is to the operator :: on the result of myFunc(t). That is why the function is not tail recursive.

Upvotes: 12

Related Questions