0
0
Kotlinprogramming~20 mins

Inner class access to outer members in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Inner Class Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of inner class accessing outer class property
What is the output of this Kotlin code?
Kotlin
class Outer {
    val greeting = "Hello"
    inner class Inner {
        fun greet() = "$greeting from Inner"
    }
}

fun main() {
    val inner = Outer().Inner()
    println(inner.greet())
}
AHello
BError: Cannot access 'greeting' from Inner
Cfrom Inner
DHello from Inner
Attempts:
2 left
💡 Hint
Remember that inner classes have access to outer class members.
Predict Output
intermediate
2:00remaining
Output when inner class shadows outer property
What will be printed by this Kotlin program?
Kotlin
class Outer {
    val value = 10
    inner class Inner {
        val value = 20
        fun printValues() {
            println(value)
            println(this@Outer.value)
        }
    }
}

fun main() {
    Outer().Inner().printValues()
}
A
10
20
B
20
10
C
20
20
D
10
10
Attempts:
2 left
💡 Hint
Use 'this@Outer' to refer to the outer class instance.
🔧 Debug
advanced
2:00remaining
Why does this code cause a compilation error?
This Kotlin code tries to access an outer class property from a nested class but fails. Why? class Outer { val name = "Outer" class Nested { fun printName() { println(name) } } } fun main() { Outer.Nested().printName() }
ANested class is not inner, so it cannot access outer class members directly.
BThe property 'name' is private and inaccessible.
CThe syntax for accessing outer class members is incorrect.
DNested classes cannot have functions in Kotlin.
Attempts:
2 left
💡 Hint
Check the difference between 'inner' and 'nested' classes in Kotlin.
Predict Output
advanced
2:00remaining
Output of inner class accessing outer class function
What is the output of this Kotlin program?
Kotlin
class Outer {
    fun outerFun() = "Outer Function"
    inner class Inner {
        fun callOuter() = outerFun()
    }
}

fun main() {
    println(Outer().Inner().callOuter())
}
AOuter Function
BError: Cannot call outerFun from Inner
Cnull
DOuter
Attempts:
2 left
💡 Hint
Inner classes can call outer class functions directly.
🧠 Conceptual
expert
2:00remaining
How to access outer class property when inner class has same property name?
In Kotlin, if an inner class has a property with the same name as the outer class, how can you access the outer class property inside the inner class?
AUse 'Outer.propertyName' directly without any qualifier.
BUse 'super.propertyName' inside the inner class.
CUse 'this@Outer.propertyName' to refer to the outer class property.
DIt's not possible to access outer class property if names clash.
Attempts:
2 left
💡 Hint
Kotlin provides a special syntax to refer to outer class instance.