0
0
Kotlinprogramming~20 mins

Local functions (nested functions) in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Local Functions Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of nested local function call
What is the output of this Kotlin code with a local function inside another function?
Kotlin
fun outer() {
    fun inner() {
        println("Hello from inner")
    }
    inner()
    println("Hello from outer")
}

fun main() {
    outer()
}
AHello from inner
B
Hello from outer
Hello from inner
CCompilation error: inner function cannot be called
D
Hello from inner
Hello from outer
Attempts:
2 left
💡 Hint
Remember that local functions can be called inside their enclosing function.
Predict Output
intermediate
2:00remaining
Value returned by nested local function
What value does the function 'outer' return when called?
Kotlin
fun outer(): Int {
    fun inner(x: Int): Int {
        return x * 2
    }
    return inner(5) + 3
}

fun main() {
    println(outer())
}
A13
B10
C8
DCompilation error: cannot return from local function
Attempts:
2 left
💡 Hint
Calculate inner(5) first, then add 3.
🔧 Debug
advanced
2:00remaining
Identify the error in nested function usage
What error does this Kotlin code produce?
Kotlin
fun outer() {
    inner()
    fun inner() {
        println("Inside inner")
    }
}

fun main() {
    outer()
}
ACompilation error: local function cannot be declared after usage
BUnresolved reference: inner
CRuntime exception: inner function not found
DNo error, prints "Inside inner"
Attempts:
2 left
💡 Hint
Check the order of function declaration and usage.
Predict Output
advanced
2:00remaining
Effect of local function modifying outer variable
What is the output of this Kotlin code?
Kotlin
fun outer() {
    var count = 0
    fun increment() {
        count += 1
    }
    increment()
    increment()
    println(count)
}

fun main() {
    outer()
}
A2
B0
C1
DCompilation error: cannot modify outer variable
Attempts:
2 left
💡 Hint
Local functions can access and modify variables from the outer function.
🧠 Conceptual
expert
2:00remaining
Scope and visibility of local functions
Which statement about local functions in Kotlin is TRUE?
ALocal functions can be declared at the top level outside any function.
BLocal functions can be accessed from any other function in the same file.
CLocal functions can be called only inside the function where they are declared.
DLocal functions can be called before their declaration anywhere in the program.
Attempts:
2 left
💡 Hint
Think about the visibility and scope rules of local functions.