Recall & Review
beginner
What does it mean that Kotlin extensions are resolved statically?
It means that extension functions are determined by the type of the variable at compile time, not by the actual object instance at runtime.
Click to reveal answer
intermediate
Given <code>open class A</code> and <code>class B : A()</code>, if you define an extension function for <code>A</code> and another for <code>B</code>, which one is called when you use a variable of type <code>A</code> holding an instance of <code>B</code>?The extension function for
A is called because extensions are resolved based on the variable's declared type, not the actual instance type.Click to reveal answer
intermediate
Why can't extension functions be overridden in Kotlin?
Because extensions are resolved statically at compile time, they are not part of the class's virtual method table and thus cannot be overridden like member functions.
Click to reveal answer
beginner
How can you call a member function instead of an extension function if both have the same signature?
The member function always takes precedence over an extension function with the same signature when called on an instance.
Click to reveal answer
beginner
Explain with a simple code example how Kotlin resolves extensions statically.
open class A
class B : A()
fun A.foo() = "A"
fun B.foo() = "B"
fun main() {
val a: A = B()
println(a.foo()) // Prints "A" because extension is resolved by variable type
}Click to reveal answer
In Kotlin, when you call an extension function on a variable, which type determines which extension is used?
✗ Incorrect
Extension functions are resolved statically based on the declared type of the variable at compile time.
If a class has a member function and an extension function with the same name and parameters, which one is called?
✗ Incorrect
Member functions always take precedence over extension functions with the same signature.
Can extension functions be overridden in subclasses in Kotlin?
✗ Incorrect
Extensions are resolved statically and are not part of the class inheritance mechanism, so they cannot be overridden.
What will this code print?
open class A
class B : A()
fun A.foo() = "A"
fun B.foo() = "B"
fun main() {
val a: A = B()
println(a.foo())
}
✗ Incorrect
The extension function for A is called because the variable a is declared as type A.
Why are Kotlin extension functions useful despite being resolved statically?
✗ Incorrect
Extensions let you add new functions to classes without changing their source code or inheritance.
Explain how Kotlin resolves extension functions and why this means they cannot be overridden.
Think about when the compiler decides which extension to call.
You got /4 concepts.
Describe a scenario with classes A and B where B inherits A, and both have extension functions. What happens when you call the extension on a variable typed as A but holding B?
Focus on the difference between declared type and actual instance.
You got /4 concepts.