Recursion and tailrec
A function may call itself. tailrec turns tail calls into loops.
Example
fun fact(n: Int): Long = if (n <= 1) 1 else n * fact(n - 1)
tailrec fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
println(fact(5))
println(gcd(48, 18))Exercise
Optimise tail calls.
fun f()Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.