Val by Delegate (Bug or feature?)


#1

Hello,

consider the following:

class GetMe {
    var a = 1
    operator fun getValue(thisRef: Any?, property: KProperty<*>): Int {
        return ++a
    }
}

private val getMe = GetMe()
private val testMe: Int by getMe

@Test
fun `I'm a playground, not a test`() {
    println(testMe)
    println(testMe)
    println(testMe)
}

We can change testMe values although it is declared as val. Shouldn’t Kotlin compiler take care of this case and not allow this kind of delegate?


#2

No. val means readonly. Not unchangeable.


#3

Another way to say it is: Val does not mean immutable
Here’s an example without delegates:

class Person {
  var _age = 1
  val age: Int get() = _age++
}

fun main() {
  val bob = Person()
  println(bob.age)
  println(bob.age)
  println(bob.age)
}

#4

Using Java terms, val merely means a getter API method. There is nothing in Java or Kotlin that hints a getter method always returns the same value.