Recall & Review
beginner
What is a custom getter in Kotlin?
A custom getter is a special function that runs when you access a property. It lets you control or change the value returned without storing it directly.
Click to reveal answer
beginner
How do you define a custom setter in Kotlin?
You define a custom setter by writing a set function inside the property. It runs when you assign a value, letting you check or modify the value before saving it.
Click to reveal answer
intermediate
Why use custom getters and setters instead of simple properties?
They let you add extra logic like validation, formatting, or lazy calculation when getting or setting a value, making your code safer and clearer.Click to reveal answer
beginner
Show a simple Kotlin property with a custom getter that returns the length of a string property.
val nameLength: Int
get() = name.length
This means whenever you ask for nameLength, it calculates and returns the length of name.
Click to reveal answer
intermediate
What happens if you define a custom setter but no backing field is used?
Without a backing field, the setter cannot store the value. You must handle storage yourself or use a backing field with the 'field' keyword to save the value.
Click to reveal answer
In Kotlin, how do you access the backing field inside a custom setter?
✗ Incorrect
Inside a custom setter or getter, 'field' refers to the actual storage of the property.
What is the default behavior if you do not define a custom getter or setter?
✗ Incorrect
Kotlin automatically provides default getter and setter that read and write the backing field.
Which keyword is used to define a custom getter in Kotlin?
✗ Incorrect
The 'get()' keyword defines a custom getter function for a property.
What happens if you try to use 'field' outside a getter or setter?
✗ Incorrect
'field' is only valid inside custom getters and setters; outside, it causes a compile error.
Why might you want to add validation in a custom setter?
✗ Incorrect
Validation in setters helps ensure only correct values are saved, avoiding bugs.
Explain how custom getters and setters work in Kotlin and why they are useful.
Think about how you control reading and writing a property.
You got /3 concepts.
Write a Kotlin property with a custom setter that only accepts positive numbers and throws an error otherwise.
Use 'set(value)' and check if value is positive.
You got /3 concepts.