Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Java 8 Trampoline for Tail Call Recursion
import java.math.BigInteger;
public class TailCallRecursion {
public interface Trampoline<V> {
V trampoline();
default V call() {
Object trampoline = this;
while (trampoline instanceof Trampoline) {
trampoline = ((Trampoline) trampoline).trampoline();
V value = (V) trampoline;
return value;
public static Trampoline factorial(final int n, final BigInteger accumulated) {
return () -> {
if (n <= 1) return accumulated;
return factorial(n - 1, accumulated.multiply(BigInteger.valueOf(n)));
public static void main(String[] args) {
System.out.println(factorial(10000, BigInteger.ONE).call());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.