You want to write a Kotlin function that calculates factorial using a local recursive function. Which code correctly implements this?
hard📝 Application Q8 of 15
Kotlin - Functions
You want to write a Kotlin function that calculates factorial using a local recursive function. Which code correctly implements this?
Afun factorial(n: Int): Int {
val fact = fun(x: Int): Int = if (x <= 1) 1 else x * fact(x - 1)
return fact(n)
}
Bfun factorial(n: Int): Int {
fun fact(x: Int) {
if (x <= 1) 1 else x * fact(x - 1)
}
return fact(n)
}
Cfun factorial(n: Int): Int {
fun fact(x: Int): Int = if (x <= 1) 1 else x * fact(x - 1)
return fact(n)
}
Dfun factorial(n: Int): Int {
fun fact(x: Int): Int = if (x == 0) 0 else x * fact(x - 1)
return fact(n)
}
Step-by-Step Solution
Solution:
Step 1: Check recursive local function syntax
fun factorial(n: Int): Int {
fun fact(x: Int): Int = if (x <= 1) 1 else x * fact(x - 1)
return fact(n)
} correctly defines a local function fact with proper recursion and base case (x <= 1 returns 1).
Step 2: Analyze other options
B lacks return type and does not return value from fact. C uses val with recursive call which causes error because fact is not fully defined when called. D has wrong base case returning 0 for 0, which breaks factorial logic.
Final Answer:
fun factorial(n: Int): Int {
fun fact(x: Int): Int = if (x <= 1) 1 else x * fact(x - 1)
return fact(n)
} -> Option C
Quick Check:
Local recursive function = fun factorial(n: Int): Int {
fun fact(x: Int): Int = if (x <= 1) 1 else x * fact(x - 1)
return fact(n)
} [OK]
Quick Trick:Use local functions for recursion inside main function [OK]
Common Mistakes:
MISTAKES
Missing return in recursive function
Wrong base case in recursion
Using val for recursive local function causing errors
Master "Functions" in Kotlin
9 interactive learning modes - each teaches the same concept differently