O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required