// Created on savesnippets.com ยท https://savesnippets.com/yXXWmsc8VWoIwO // 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 findLast(list: List, 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 }