Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Learning Kotlin: By [Snippet]

DZone's Guide to

Learning Kotlin: By [Snippet]

Want to learn more about the by keyword in Kotlin? Check out this code snippet on using the by keyword to delegate the getter/setter into separate classes.

· Java Zone ·
Free Resource

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

The fourth set of Koans looks at properties, while the first two look at getters and setters. If you coming from another programming language, then these should work the way you expect. This post will look at the amazing by keyword in the third and fourth examples. The by keyword enables us to delegate the getter/setter to be handled by a separate class, which means that common patterns can be extracted and reused.

Out of the box, there are five built-in options, which I will expand into in their own posts, but for now, let us build our own delegate class. In this example, we can assign any value — the result we get is always HAHAHA. We could store the result in the instance and return the value assigned, but we do not have to. The key takeaway is that we have ensured the logic for our properties in one reusable place, rather than scattered across multiple getters and setters.

import kotlin.reflect.KProperty

class User {
    var name : String by Delegate()
    var eyeColour : String by Delegate();
}

class Delegate {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        println("$thisRef, thank you for delegating '${property.name}' to me!")
        return "HAHAHA"
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        println("$value has been assigned to '${property.name}' in $thisRef.")
    }
}

fun main(args: Array<String>) {
    val user = User()
    user.name = "Robert"
    user.eyeColour = "Green"
    println("My word ${user.name} but your eyes are ${user.eyeColour}")
}


How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Topics:
java ,kotlin ,code ,code snippet ,tutorial ,by ,by keyword ,keywords

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}