Look at this Kotlin class with a custom getter. What will be printed when println(box.area) runs?
class Box(val width: Int, val height: Int) { val area: Int get() = width * height } fun main() { val box = Box(3, 4) println(box.area) }
Remember the getter calculates the area by multiplying width and height.
The custom getter returns width * height. For width=3 and height=4, area is 12.
Consider this Kotlin class with a custom setter. What will be printed after person.age = 25 and println(person.age)?
class Person { var age: Int = 0 set(value) { field = if (value >= 0) value else 0 } } fun main() { val person = Person() person.age = 25 println(person.age) }
The setter sets the field only if the value is non-negative.
The setter assigns field = value if value is >= 0. Since 25 is positive, age becomes 25.
Examine this Kotlin class. Why does setting counter.value = 5 cause a stack overflow?
class Counter { var value: Int = 0 set(value) { field = value } } fun main() { val counter = Counter() counter.value = 5 println(counter.value) }
Check what happens when the setter assigns to 'value' instead of 'field'.
Inside the setter, assigning to 'value' calls the setter again, causing infinite recursion and stack overflow. The correct way is to assign to 'field'.
Why do Kotlin custom setters and getters use the field keyword inside their bodies?
Think about what happens if you assign to the property name inside its setter.
The field keyword accesses the backing field that stores the property's value. Using it prevents recursive calls to the setter or getter.
Analyze this Kotlin code. What will be printed after account.balance = -100 and println(account.balance)?
class BankAccount { var balance: Int = 0 set(value) { field = if (value < 0) 0 else value } } fun main() { val account = BankAccount() account.balance = -100 println(account.balance) }
The setter changes negative values to zero.
The setter checks if the value is negative. If yes, it sets balance to 0. Since -100 is negative, balance becomes 0.