Kotlin - Usefulness of "computed" var properties?

A "computed" var property with an unused backing field should be a "computed" val property.

If you are not going to use the backing field in your example then Banana.color shouldn't be a var but a val. e.g.:

class Banana {
    var ripeness = 1

    val color: String
        get() = when {
            ripeness > 80 -> "brown"
            ripeness > 50 -> "yellow"
            else -> "green"
        }
}

On the other hand, if you actually wanted to make your "computed" property overridable in some cases then you would need to actually use the backing field. e.g.:

class Banana {
    var ripeness = 1

    var color: String = "green"
        get() = when {
            ripeness > 80 -> "brown"
            ripeness > 50 -> "yellow"
            else -> field
        }
}

Beware of val ... get(), the behavior migth be very surprising:

class Val {
    val millis: Long = System.currentTimeMillis()
}
class ValGet {
    val millis: Long
        get() = System.currentTimeMillis()
}

val v = Val()
val g = ValGet()
for(i in 0..4) {
    println("val:" +  v.millis + " valget:"+g.millis)
    Thread.sleep(7)
}

What's the use of val if a val x: Int cannot be relied upon to be the same when referenced twice? Apparently it even works for overrides if the parent is sufficiently open, an abstract val looksQuiteLikeImmutable : Int can be very misleading. Feels like groovy all over again... (At least this is what I observe in 1.4.21)

Tags:

Kotlin