我正在用TornadoFX做第一次实验,遇到了一个我不明白的问题。

我有一个对象Wind:

enum class Direction(val displayName: String, val abbrevation: String, val deltaX: Int, val deltaY: Int) {

    NORTH("Észak", "É", 0, -1),
    NORTH_EAST("Északkelet", "ÉK", 1, -1),
    EAST("Kelet", "K", 1, 0),
    SOUTH_EAST("Délkelet", "DK", 1, 1),
    SOUTH("Dél", "D", 0, 1),
    SOUTH_WEST("Délnyugat", "DNy", -1, 1),
    WEST("Nyugat", "Ny", -1, 0),
    NORTH_WEST("Északnyugat", "ÉNy", -1, -1);

    val diagonal: Boolean = deltaX != 0 && deltaY != 0
    val degree: Double = ordinal * 45.0

    fun turnClockwise(eighth: Int = 1) = values()[(ordinal + eighth) umod 8]
    fun turnCounterClockwise(eighth: Int = 1) = values()[(ordinal - eighth) umod 8]
    fun turn(eighth: Int = 1) = if (eighth < 0) turnCounterClockwise(eighth.absoluteValue) else turnClockwise(eighth)

    infix operator fun plus(eighth: Int) = turn(eighth)
    infix operator fun minus(eighth: Int) = turn(-eighth)

    infix operator fun minus(other: Direction) = (ordinal - other.ordinal) umod 8
}

object Wind {

    val directionProperty = SimpleObjectProperty<Direction>(Direction.NORTH)
    var direction: Direction
        get() = directionProperty.value
        set(value) {
            println("SET WIND: $value")
            directionProperty.value = value
        }
}

我想将旋转变换绑定(bind)到风向的设置。

当我使用旧的JavaFX样式时,它可以工作:
rot.angleProperty().bind(
    createDoubleBinding(
        Callable {
            println("Direction: ${Wind.direction}");
            Wind.directionProperty.value.degree * 45
        },
        Wind.directionProperty))

当我尝试使用更优雅的Kotlin风格的版本时,它没有绑定(bind):
rot.angleProperty().doubleBinding(rot.angleProperty() ) {
    println("Direction: ${Wind.direction}")
    Wind.directionProperty.value.degree * 45
}

我错过了什么?

最佳答案

doubleBinding()函数创建Binding,但未将其绑定(bind)到任何内容。

实际上,我们有两种创建此绑定(bind)的方法:

  • doubleBinding(someProperty) { ... }。对属性(this)进行操作,希望您返回Double。它不能为空。
  • someProperty.doubleBinding() { ... }将该值作为参数接收,并希望您返回Double。该参数可为空,因此您需要考虑该

  • 剩下两个选择:
    rot.angleProperty().bind(doubleBinding(Wind.directionProperty) {
        value.degree * 45
    })
    

    要么
    rot.angleProperty().bind(Wind.directionProperty.doubleBinding {
        it?.degree ?: 0.0 * 45
    })
    

    您选择哪一个主要取决于口味,尽管在某些情况下一个会比另一个更自然。

    07-24 20:24