DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Languages
  4. Learning Kotlin: the Observable Delegate

Learning Kotlin: the Observable Delegate

Want to learn more about types of delegates in Kotlin and how to use them? Check out this tutorial to learn more about using the observable delegate.

Robert Maclean user avatar by
Robert Maclean
·
Sep. 07, 18 · Tutorial
Like (3)
Save
Tweet
Share
10.98K Views

Join the DZone community and get the full member experience.

Join For Free

Following our introduction to the by operator and delegates, this post looks at the second of the five built-in delegates, observable.

The next built-in delegate is observable. This allows us to intercept all attempts to set the value. You can do this with a setter, but remember you would need to duplicate that setter code every time. With the observable, you can build the logic once and reuse it over and over again.

Once again, let us start by looking at how we would do this without the delegated property:

class User() {
    var name: String = "<NO VALUE>"
    set(value) {
        DataChanged("name", name, value)
    }

    var eyeColour: String = "<NO VALUE>"
    set(value) {
        DataChanged("eyeColour", name, value)
    }

    fun DataChanged(propertyName: String, oldValue: String, newValue: String) {
        println("$propertyName changed! $oldValue -> $newValue")
    }
}

fun main(args:Array<String>) {
    val user = User()
    user.name = "Robert"
    user.eyeColour = "Green"
}


Note here that we need to do the setter twice manually, and in each one, we will need to change a value, which you know will get missed when you copy and paste the code.

In the next example, we change to use the observable delegate, which allows us to easily call the same function.

While I don't recommend this for production, I did — in this example — call it in two different ways. For age, as the second parameter is a lambda, I just created that and passed the parameters to my function. This is how all the demos normally show the usage of this. For name though, since my function has the same signature as the lambda, I can pass it directly to the observable, which seems much nicer to me. Though, since we need to pass a reference to our function, we need to prefix it with ::.

package sadev

import kotlin.properties.Delegates
import kotlin.reflect.KProperty

class User() {
    var name: String by Delegates.observable("<NO VALUE>", ::DataChanged)

    var eyeColour: String by Delegates.observable("<NO VALUE>") { property, old, new ->
DataChanged(property, old, new)
    }

    fun DataChanged(property: KProperty<*>, oldValue: String, newValue: String) {
        println("${property.name} changed! $oldValue -> $newValue")
    }
}

fun main(args:Array<String>) {
    val user = User()
    user.name = "Robert"
    user.eyeColour = "Green"
}
Kotlin (programming language) Pass (software) POST (HTTP) Build (game engine) Production (computer science) Property (programming) Operator (extension)

Published at DZone with permission of Robert Maclean, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • DZone's Article Submission Guidelines
  • How to Submit a Post to DZone
  • REST vs. Messaging for Microservices
  • HTTP vs Messaging for Microservices Communications

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: