简体   繁体   中英

Trying to implement the TornadoFX "Motivational example"

I'm trying to implement the motivational example from this page: https://docs.tornadofx.io/0_subsection/1_why_tornadofx

For this I need a data class Person as defined here:

class Person(id: Int, name: String, birthday: LocalDate) {
    val idProperty = SimpleIntegerProperty(id)
    var id by idProperty

    val nameProperty = SimpleStringProperty(name)
    var name by nameProperty

    val birthdayProperty = SimpleObjectProperty(birthday)
    var birthday by birthdayProperty

    val age: Int get() = Period.between(birthday, LocalDate.now()).years
}

To do this it was neccessary to make the following imports:

import javafx.beans.property.SimpleIntegerProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.SimpleStringProperty
import java.time.LocalDate
import java.time.Period

However, if I try to run the example I get the following error:

Kotlin: Property delegate must have a 'getValue(Person, KProperty<*>)' method. None of the following functions is suitable: 
public open fun getValue(): Int! defined in javafx.beans.property.SimpleIntegerProperty

I can circumvent this by not using delegate types and setting the properties like this:

    val idProperty = SimpleIntegerProperty(id)
    var id: Int
        get() = idProperty.value
        set(value) { idProperty.value = value}

But that seems to defeat the point of using delegates in TornadoFX when this is their motivational example for using it.

Here's what I found on delegate types: https://edvin.gitbooks.io/tornadofx-guide/content/part2/Property_Delegates.html

That doesn't help with getting the shorthand of var id by idProperty to work though.

Can somebody point me in the right direction here?

You need to also import the following:

import tornadofx.getValue
import tornadofx.setValue

Those are extension operator functions defined for various types in JavaFX (eg, properties, observable values, etc.) so that those types can be used as delegates. But those function aren't defined in those types, thus the need for the additional imports.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM