What's Kotlin Backing Field For?

后端 未结 5 1950
猫巷女王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条回答
  •  长发绾君心
    2021-01-29 22:28

    My understanding is using field identifier as a reference to the property's value in get or set, when you want to change or use the property's value in get or set.

    For example:

    class A{
        var a:Int=1
            get(){return field * 2}    // Similiar to Java: public int geta(){return this.a * 2}
            set(value) {field = value + 1}
    }
    

    Then:

    var t = A()
    println(t.a)    // OUTPUT: 2, equal to Java code: println(t.a * 2)
    t.a = 2         // The real action is similar to Java code: t.a = t.a +1
    println(t.a)    // OUTPUT: 6, equal to Java code: println(t.a * 2)
    

提交回复
热议问题