Kotlin custom Getter makes `val` and `var` confusing?

use*_*613 7 kotlin

In Kotlin, var is mutable and val should be assigned only once.

However, consider val foo in the following example:

var counter = 0

val foo: String
  get(){
    counter++
    return "val$counter"
  }

fun main(): String {
    val a = foo
    val b = foo
    val c = foo
    return "we got: $a $b $c"
    // output: we got: val1 val2 val3
}
Run Code Online (Sandbox Code Playgroud)

The get() method is executed each time we try to access foo, resulting different values for val.

Since the value of foo is changing, I tried to use var. The compiler then complained about "Property must be initialized". So I had to give it a default value:

var foo: String = "default value that will never be used"
  get(){
    counter++
    return "val$counter"
  }
Run Code Online (Sandbox Code Playgroud)

I don't like either approach here. What's the correct practice?

Ale*_*nov 5

在Kotlin中,var是可变的,并且val应该只分配一次。

对于局部变量,是的。对于属性,不是真的:val意思是“只有吸气剂”,var意思是“既有吸气剂又有吸气剂”。这个getter(和setter)可以做任何事情。例如,您每次可以只返回一个随机值。

一个例外是重新分配的后备字段val

val foo: Int = 0
  get(){
    field++
    return field
  }
Run Code Online (Sandbox Code Playgroud)

不会编译。