Extension Functions & Properties Interview Questions
KOTLIN › Types & Classes
What are extension functions, and how are they compiled?
What a strong answer covers: They let you add functions to a type you don't own, like fun String.isEmail(): Boolean, called as if they were members. They compile to static functions taking the receiver as the first parameter, so they don't modify the class, can't access private members, and add no runtime overhead beyond a static call.
Are extension functions resolved statically or dynamically? What happens if a class has a member function with the same signature?
What a strong answer covers: Statically, by the declared type of the variable, not the runtime type: if Shape.name() and Circle.name() are extensions and you call it on a val s: Shape = Circle(), you get Shape's. If a member with the same signature exists, the member always wins and the extension is shadowed.
Can extension properties have backing fields? What can you use them for?
What a strong answer covers: No, there's nowhere to store state on an existing class, so extension properties must be computed from the receiver: val View.isVisible get() = visibility == VISIBLE, or val Context.dataStore by preferencesDataStore(...) where the delegate holds the storage at top level. They're good for derived values and convenience accessors.
When do extension functions make an API worse? What guidelines do you follow on a team?
What a strong answer covers: Problems: too many extensions on common types like String or Context pollute autocomplete across the codebase; behaviour becomes hard to find because it isn't on the class; extensions that depend on hidden global state are hard to test. Guidelines: keep them private or internal, close to where they're used, prefer them for pure utility and adapting APIs, and put core behaviour on the class itself.
Explain extension functions with receivers in lambdas, like apply or a DSL builder. How does a type-safe builder work?
What a strong answer covers: A lambda typed T.() -> Unit has T as its receiver, so inside it 'this' is a T and you can call its members directly. A builder like html { body { p("hi") } } creates the object, passes a lambda with that receiver to configure it, and returns it. @DslMarker stops inner lambdas from implicitly calling outer receivers' functions. Compose's Modifier chains and Gradle's Kotlin DSL use the same idea.