Member-only story

Understand “by” Delegated Properties in Kotlin

Simple way to understand “by” operator (used for delegated properties) in Kotlin and the reasons to use it.

--

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"
// property get
println(example1.value)
}

Output:

property set value from null to example1
property get value: example1
example1

Please note that the field here is an implicit field. To learn more about Properties and Fields in Kotlin, refer to this article.

The problem of this is I need to implement this custom get() and set() for all the properties that I would like to monitor. For example, anotherValue above is the boilerplate code. To reduce the boilerplate code, we use by operator - delegated properties.

“by” Delegated Properties

--

--

No responses yet