Kotlin Kotlin Extensions and Delegates 1 — Questions and Answers
Question 1: What is an extension function in Kotlin?
- A function defined inside a subclass
- A function added to an existing class without modifying its source code (Correct answer)
- A function that extends the return type
- An overloaded function
Correct answer: A function added to an existing class without modifying its source code
Extension functions allow you to add new functions to existing classes without inheriting from them or using decorators.
Question 2: Can extension functions access private members of the extended class?
- Yes, always
- No, they can only access public and internal members (Correct answer)
- Yes, but only within the same module
- Yes, but only for data classes
Correct answer: No, they can only access public and internal members
Extension functions do not have access to private or protected members of the class they extend; they can only use publicly visible APIs.
Question 3: What is an extension property in Kotlin?
- A property added to an existing class without modifying its source (Correct answer)
- A property that extends the type of another property
- A property with a custom getter and setter
- A delegated property
Correct answer: A property added to an existing class without modifying its source
Extension properties add computed properties to existing classes without modifying them, but they cannot have backing fields.
Question 4: What does `by lazy` do in Kotlin?
- Creates a background thread
- Initializes a property lazily on first access using a lambda (Correct answer)
- Marks a property as nullable
- Delegates a property to another object
Correct answer: Initializes a property lazily on first access using a lambda
`by lazy { }` creates a property that is computed only once on first access and cached for subsequent reads.
Question 5: Which standard delegate observable notifies you when a property value changes?
- lazy
- vetoable
- observable (Correct answer)
- notNull
Correct answer: observable
`Delegates.observable` calls a handler function whenever the property value is changed, receiving the old and new values.
Question 6: What does `by` keyword do in Kotlin class declarations?
- Marks the class as internal
- Delegates interface implementation to another object (Correct answer)
- Indicates the class extends another
- Creates a companion object
Correct answer: Delegates interface implementation to another object
The `by` keyword in class declarations enables delegation, where method calls on the class are forwarded to another object automatically.
What is an extension function in Kotlin?