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.

def​ explore(count: ​Int​, words: ​List​[​String​]) : ​Int​ =
if​(words.size == 0)
countPalindrome(count, words) ...

Get Pragmatic Scala now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.