// Without tailrec — deep recursion blows the stack
fun factorial(n: Long, acc: Long = 1): Long =
if (n <= 1) acc else factorial(n - 1, acc * n)
// With tailrec — compiler emits a loop, no stack growth
tailrec fun factorialSafe(n: Long, acc: Long = 1): Long =
if (n <= 1) acc else factorialSafe(n - 1, acc * n)
// Classic — list iteration
tailrec fun <T> findLast(list: List<T>, index: Int = 0): T? = when {
list.isEmpty() -> null
index == list.lastIndex -> list[index]
else -> findLast(list, index + 1)
}
fun main() {
println(factorialSafe(20)) // 2432902008176640000
// Without tailrec, factorial(100_000) would StackOverflow.
println(factorialSafe(100_000) > 0) // true (BigInt-style overflow but no SOE)
println(findLast(listOf("a", "b", "c", "d"))) // d
}
Create a free account and build your private vault. Share publicly whenever you want.