Understand “by” Delegated Properties in Kotlin
Simple way to understand “by” operator (used for delegated properties) in Kotlin and the reasons to use it.
4 min readDec 9, 2022
When I first learned Kotlin, the by
operator is an alien to me. What the hell is that? In this article, I'm going to provide a simple example to show the reasons why we want to use this by
operator.
Custom Property get() and set()
Let’s say I want to create a custom property get()
and set()
to print out something when the property value is read and set. I will do something like this.
class PropertyAccessExample {
var value: String? = null
get() {
println("property get value: $field")
return field
}
set(value: String?) {
println("property set value from $field to $value")
field = value
}
var anotherValue: String? = null
get() {
println("property get value: $field")
return field
}
set(value: String?) {
println("property set value from $field to $value")
field = value
}
}
fun main() {
val example1 = PropertyAccessExample()
// property set
example1.value = "example1"
//…