Careeroza
Local Functions and Recursion
Local Functions
Example
A function can be declared inside another function. It can use the outer function's variables and keeps helper logic private.
fun validateSignup(name: String, phone: String, pin: String): List<String> {
val errors = mutableListOf<String>()
fun check(condition: Boolean, message: String) {
if (!condition) errors.add(message)
}
check(name.isNotBlank(), "Name is required")
check(phone.length == 10 && phone.all { it.isDigit() }, "Phone must be 10 digits")
check(pin.length == 4, "PIN must be 4 digits")
return errors
}
fun main() {
println(validateSignup("Asha", "9876543210", "1234"))
println(validateSignup("", "98765", "12"))
}Output
[] [Name is required, Phone must be 10 digits, PIN must be 4 digits]
Recursion
Example
A recursive function calls itself. It needs a base case that stops the recursion.
fun factorial(n: Int): Long = if (n <= 1) 1 else n * factorial(n - 1)
fun fib(n: Int): Int = if (n < 2) n else fib(n - 1) + fib(n - 2)
tailrec fun sumDigits(n: Int, acc: Int = 0): Int =
if (n == 0) acc else sumDigits(n / 10, acc + n % 10)
fun main() {
println(factorial(5))
println(factorial(20))
println((0..10).map { fib(it) })
println(sumDigits(98765))
}Output
120 2432902008176640000 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] 35
Note: tailrec tells the compiler to turn a tail-recursive function into a loop, so it cannot overflow the stack.