Challenge - 5 Problems
Inner Class Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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()) }
Attempts:
2 left
💡 Hint
Remember that inner classes have access to outer class members.
✗ Incorrect
In Kotlin, an inner class can access members of its outer class instance. Here, 'greeting' is accessed directly inside the inner class method.
❓ Predict Output
intermediate2: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() }
Attempts:
2 left
💡 Hint
Use 'this@Outer' to refer to the outer class instance.
✗ Incorrect
The inner class has its own 'value' property which shadows the outer class's 'value'. 'value' alone refers to inner's property, 'this@Outer.value' refers to outer's property.
🔧 Debug
advanced2: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()
}
Attempts:
2 left
💡 Hint
Check the difference between 'inner' and 'nested' classes in Kotlin.
✗ Incorrect
In Kotlin, nested classes are static by default and do not hold a reference to the outer class instance. Only inner classes can access outer class members directly.
❓ Predict Output
advanced2: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()) }
Attempts:
2 left
💡 Hint
Inner classes can call outer class functions directly.
✗ Incorrect
The inner class method 'callOuter' calls the outer class function 'outerFun' directly, so it returns 'Outer Function'.
🧠 Conceptual
expert2: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?
Attempts:
2 left
💡 Hint
Kotlin provides a special syntax to refer to outer class instance.
✗ Incorrect
The syntax 'this@Outer' refers to the instance of the outer class, allowing access to its members even if shadowed.