Anti-Patterns
It is tempting to put data conversion or normalization in a custom setter. However, this means that the getter will not return what was last set in the setter:
var something: String = "This is the 'something' value"
get() = field
set(value) { field = value.toUpperCase() }
fun main() {
println(something)
something = "This is different"
println(something)
}
Running this gives us:
This is the 'something' value
THIS IS DIFFERENT
Not only does the value returned by the second something
reference not match what we set on it, but the initializer bypasses the setter, possibly resulting in “invalid” data.
Also, be very careful when making a custom accessor be expensive, such as being slow. Developers will assume that accessors are cheap and may not realize the cost of calling your custom ones.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.