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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With