Kotlin Kotlin Extensions and Delegates 2 — Questions and Answers
Question 1: What is property delegation in Kotlin?
- Passing a property to a function
- Delegating the implementation of a property's get/set to another object (Correct answer)
- Creating a copy of a property
- Making a property abstract
Correct answer: Delegating the implementation of a property's get/set to another object
Property delegation lets you hand off the `get` and `set` implementations to a delegate object, enabling reusable property behavior.
Question 2: What does `Delegates.notNull()` do in Kotlin?
- Ensures a property is initialized before access, throwing if accessed before assignment (Correct answer)
- Marks a property as non-nullable
- Creates a property with a default value
- Delegates to a companion object
Correct answer: Ensures a property is initialized before access, throwing if accessed before assignment
`Delegates.notNull()` creates a property that throws an `IllegalStateException` if read before being assigned a value.
Question 3: What is `lateinit` used for in Kotlin?
- Lazy initialization of nullable properties
- Allowing non-nullable var properties to be initialized after declaration without using null (Correct answer)
- Declaring properties in interfaces
- Marking properties as thread-safe
Correct answer: Allowing non-nullable var properties to be initialized after declaration without using null
`lateinit` allows non-nullable `var` properties to be declared without immediate initialization, useful for dependency injection and unit tests.
Question 4: What is the difference between `lazy` and `lateinit` in Kotlin?
- No difference
- `lazy` is for val properties with computed initialization; `lateinit` is for var properties initialized externally (Correct answer)
- `lazy` supports primitives; `lateinit` does not
- `lateinit` is thread-safe; `lazy` is not
Correct answer: `lazy` is for val properties with computed initialization; `lateinit` is for var properties initialized externally
`lazy` is used with `val` and initializes via a lambda on first access, while `lateinit` is for `var` properties that will be set later by external code.
Question 5: Which scope function is best for configuring a newly created object?
- let
- run
- apply (Correct answer)
- also
Correct answer: apply
`apply` calls a block with the object as `this`, allows you to configure it in place, and returns the object — perfect for builder-style setup.
Question 6: What is a `vetoable` delegate in Kotlin?
- A delegate that makes a property read-only after first assignment
- A delegate that lets you veto (reject) a new value before it is set (Correct answer)
- A delegate that logs property changes
- A delegate that synchronizes access
Correct answer: A delegate that lets you veto (reject) a new value before it is set
`Delegates.vetoable` calls a handler when a value is about to be assigned; if the handler returns `false`, the assignment is rejected.
What is property delegation in Kotlin?