Extension Functions & Properties Flashcards
KOTLIN › Types & Classes
- Are extension functions dispatched statically or dynamically (virtually)?
- Statically. The compiler picks the function from the receiver's declared/compile-time type, not the runtime type, so there is no virtual dispatch and no real overriding.
- If a class has a member function and an extension with the identical signature, which is called?
- The member function always wins. Extensions can only add new functions or overload with a different signature; they can never override or shadow an existing member.
- Given fun Shape.name()="Shape" and fun Rectangle.name()="Rectangle", what does a function taking a Shape print when passed a Rectangle?
- "Shape". Resolution uses the static parameter type Shape, ignoring that the runtime object is a Rectangle.
- Why can't an extension property have a backing field or an initializer?
- Extensions add no real members to the class, so there is nowhere to store state. You must define an explicit get() (and set()), often delegating to an external map.
- What does a nullable receiver type let you do, e.g. fun Any?.show()?
- It lets the extension be called even when the receiver is null. Inside, you check this == null before touching members, avoiding a separate null check at the call site.
- Can an extension access private or protected members of the class it extends?
- No. A top-level extension is compiled outside the class, so it only sees the public/internal API, just like any external caller.
- Under the hood, what is an extension function compiled to on the JVM?
- A static (top-level) method whose first parameter is the receiver. That is exactly why dispatch is static and the original class is never modified.
- In an extension declared inside a class, what are the dispatch receiver and the extension receiver?
- The dispatch receiver is the enclosing class instance (resolved virtually at runtime); the extension receiver is the type being extended (resolved statically at compile time).
- What is Android KTX and which Kotlin features power it?
- A set of AndroidX extensions over Jetpack/platform APIs to cut boilerplate, built on extension functions/properties, lambdas-with-receiver, default args, inline functions, and coroutines (e.g. SharedPreferences.edit{}, viewModels(), viewModelScope).