I am looking into scala TCO and have written the following code
import scala.annotation.tailrec
final def tailReccursionEx(str:String):List[String]={
@tailrec
def doTailRecursionEx(str:String,pos:Int,accu:List[String]):List[String]={
if(pos==str.length) return accu
else{
doTailRecursionEx(str,pos+1,accu++accu.foldLeft(List[String](str(`pos`).toString)){
(l,ch)=>l:+ch+str(`pos`)})
}
}
doTailRecursionEx(str,0,List[String]())
}
I have passed the @tailrec test and I believe that my function is self-recursive tail call. Yet, when I look into the java byte code with
javap -c -private RecursionEx\$\$anonfun\$doTailRecursionEx\$1\$1
I don’t see the promised goto for the TCO for self-recursive function. Here is the bytecode.
public RecursionEx$$anonfun$doTailRecursionEx$1$1(java.lang.String, int);
Code:
0: aload_0
1: aload_1
2: putfield #35; //Field str$2:Ljava/lang/String;
5: aload_0
6: iload_2
7: putfield #41; //Field pos$1:I
10: aload_0
11: invokespecial #93; //Method scala/runtime/AbstractFunction2."<init>":()V
14: return
}
I think you need to run
javapon a different generated class file. The file you are examining at present corresponds to the closure you use as part offoldLeft. If you try looking at the “RecursionEx$.class” file you should see the tail call recursion. When I compile the code:and then run
javap -c -private RecursionEx$I see the following for the relevant section of code:with a
gotoat the end, just as you would expect.