Trampoline Calls

Even though the TCO support in Scala is quite powerful, it’s limited. The compiler only detects direct recursions—that is, a function calling itself. If two functions call each other, known as a trampoline call, Scala doesn’t detect such recursion and performs no optimization.

Though the Scala compiler provides no support for trampoline calls, we can use the TailRec class to avoid stack overflow issues.

Let’s first take a look at an example with trampoline calls that will run into the stack overflow error for large input values.

ProgrammingRecursions/words.scala
 
import​ scala.io.Source._
 
 
def​ explore(count: ​Int​, words: ​List​[​String​]) : ​Int​ =
 
if​(words.size == 0)
 
count
 
else
 
countPalindrome(count, words) ...

Get Pragmatic Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.