kotlin

How to make variable return different values on access?


I have a homework question "Implement a val property that returns a different value on each access"

I can imagine how I can return different values with function, but not with variable. Is there some "linux-like" link to this function in Kotlin I should make?


Solution

  • This is a simple example. I recommend reading Kotlin's documentation on getters and setters.

    class CustomGetter {
        private var underlyingField: Int = 0
    
        private var alwaysHigher: Int = this.underlyingField
        get() {
            this.underlyingField++
            field = underlyingField
            return field
        }
    }