Search code examples
kotlintornadofx

Please Explain Property Delegates


I am trying to learn Kotlin and TornadoFX. One thing I keep seeing is code like this:

val TextProperty = SimpleStringProperty()
var text by Textproperty

I've been reading up on the documentation

https://edvin.gitbooks.io/tornadofx-guide/content/part2/Property%20Delegates.html

so I've "absorbed" that they are useful for when values in a model change, but I need further help really grasping the concept. Something doesn't quite seem to be clicking. Does anyone have any examples, videos, etc. that demonstrate the purpose and usefulness of these property delegates?


Solution

  • The important point here is that JavaFX requires or at least prefers observable properties. Instead of declaring a mutable property, you would declare one of the JavaFX property types, depending on what property type you want (String, Double, Int etc). All you really need is to declare this property:

    class Customer {
        val ageProperty = SimpleIntegerProperty()
    }
    

    You can get by with just this, without using any delegates. However, if you want to mutate this property, you need to change the value property inside the property you defined, so the code looks like this:

    customer.ageProperty.value = 42

    This is cumbersome, so to make it simple, you'd want to add getters and setters. Doing this manually would look something like this:

    val ageProperty = SimpleIntegerProperty()
        var age: Int
            get() = ageProperty.value
            set(value) { ageProperty.value = value }
    

    Now you can set the age of a Customer like this:

    customer.age = 42

    This is much more convenient, but you'd have to declare all that code for each property, so in TornadoFX we introduced property delegates that takes care of all that with a simple statement, so:

    val ageProperty = SimpleIntegerProperty()
    var age by ageProperty
    

    The end result is the same, without you having to do any of the heavy lifting.

    Just to be clear, this explains the property delegates, not why JavaFX properties are useful. JavaFX properties allow you to bind to a UI element, like a text field for example. Changes to the text field will be written back into the property, and changes to the property would be written back to the UI.