What's Kotlin Backing Field For?

后端 未结 5 1952
猫巷女王i
猫巷女王i 2021-01-29 21:43

As a Java developer, the concept of a backing field is a bit foreign to me. Given:

class Sample {
    var counter = 0 // the initializer value is written directly         


        
5条回答
  •  猫巷女王i
    2021-01-29 22:31

    The terminology backing field is filled with mystery. The keyword used is field. The get/set methods, follows immediately next to the member variable that is about to be get or set through this door protective methods mechanism. The field keyword just refers to the member variable that is to be set or get. At present Kotlin, you cannot refer to the member variable directly inside the get or set protective door methods because it will unfortunately result to infinite recursion because it will re-invoke the get or set and thus leds the runtime down into the deep abyss.

    In C# though, you can directly reference the member variable inside the getter/setter methods. I am citing this comparison to present the idea that this field keyword is how the present Kotlin is implementing it but I do hope it will be removed in later versions and allow us to directly reference the member variable directly without resulting to infinite recursion.

提交回复
热议问题