What if you could control property changes automatically without extra functions everywhere?
Why Custom getters and setters in Kotlin? - Purpose & Use Cases
Imagine you have a class with a property, and you want to control how its value is read or changed. Without custom getters and setters, you have to write extra functions everywhere to check or modify the value manually.
This manual approach is slow and easy to forget. You might miss checks or updates, causing bugs. It also clutters your code with repetitive functions, making it hard to read and maintain.
Custom getters and setters let you define special code that runs automatically when you get or set a property. This keeps your checks and updates in one place, making your code cleaner and safer.
private var age: Int = 0 fun setAge(value: Int) { if (value >= 0) age = value } fun getAge(): Int { return age }
var age: Int = 0 set(value) { if (value >= 0) field = value } get() = field
You can easily add rules and logic to property access, making your code more reliable and easier to understand.
For example, in a banking app, you can prevent setting a negative balance by adding a custom setter that blocks invalid values automatically.
Manual property control is repetitive and error-prone.
Custom getters and setters centralize logic for cleaner code.
This makes your programs safer and easier to maintain.
Practice
Solution
Step 1: Understand property access
Custom getters and setters allow you to define how a property value is retrieved or changed.Step 2: Identify their purpose
They help control and protect the data by customizing read/write behavior.Final Answer:
To control how properties are read and written -> Option CQuick Check:
Custom getters/setters = control property access [OK]
- Confusing getters/setters with class creation
- Thinking they define functions outside classes
- Assuming they import libraries
age?Solution
Step 1: Check property mutability
Setter can only be defined forvar, notval.Step 2: Verify setter syntax
The setter usesset(value) { field = value }to assign the new value.Final Answer:
var age: Int set(value) { field = value } -> Option AQuick Check:
Setter syntax = set(value) { field = value } [OK]
- Using get instead of set for setter
- Defining setter on val property
- Reversing field and value in setter
class Person {
var name: String = ""
get() = field.uppercase()
set(value) { field = value.trim() }
}
fun main() {
val p = Person()
p.name = " alice "
println(p.name)
}Solution
Step 1: Analyze setter behavior
Setter trims the input, so " alice " becomes "alice" stored infield.Step 2: Analyze getter behavior
Getter returns the stored value in uppercase, so "alice" becomes "ALICE".Final Answer:
ALICE -> Option AQuick Check:
Setter trims, getter uppercases = ALICE [OK]
- Ignoring trimming in setter
- Not converting to uppercase in getter
- Assuming original input prints
class Box {
var size: Int = 0
get() = field
set(value) {
if (value > 0) field = value
else field = 0
}
fun printSize() {
println(size)
}
}Solution
Step 1: Check setter logic
Setter assignsfield = valueif positive, else 0. This is valid.Step 2: Check getter and property type
Getter returnsfield, which is correct. Property is var, so setter allowed.Final Answer:
No error, code works fine -> Option BQuick Check:
Setter and getter correct = no error [OK]
- Thinking getter can't use field
- Assuming setter must always assign value
- Confusing var and val for setters
score that never stores a negative value. Which custom setter implementation ensures this correctly?Solution
Step 1: Understand requirement
Property must never store negative values; negative inputs become zero.Step 2: Evaluate each setter
var score: Int = 0 set(value) { field = if (value < 0) 0 else value } setsfieldto 0 if value is negative, else stores value correctly.Step 3: Check other options
A stores negative of value, which can be positive or negative incorrectly; B only sets field if negative, ignoring positive values; C stores negatives unchanged.Final Answer:
var score: Int = 0 set(value) { field = if (value < 0) 0 else value } -> Option DQuick Check:
Setter with if-else ensures no negatives [OK]
- Not assigning field for positive values
- Allowing negative values to be stored
- Incorrectly negating values
Ready to prove it?
Pass the test and this pattern moves unknown
