What's Kotlin Backing Field For?

后端 未结 5 1995
猫巷女王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:17

    Initially, I too had a tough time understanding this concept. So let me explain it to you with the help of an example.

    Consider this Kotlin class

    class DummyClass {
        var size = 0;
        var isEmpty
            get() = size == 0
            set(value) {
                size = size * 2
            }
    }
    

    Now when we look at the code, we can see that it has 2 properties i.e - size (with default accessors) and isEmpty(with custom accessors). But it has only 1 field i.e. size. To understand that it has only 1 field, let us see the Java equivalent of this class.

    Go to Tools -> Kotlin -> Show Kotlin ByteCode in Android Studio. Click on Decompile.

       public final class DummyClass {
       private int size;
    
       public final int getSize() {
          return this.size;
       }
    
       public final void setSize(int var1) {
          this.size = var1;
       }
    
       public final boolean isEmpty() {
          return this.size == 0;
       }
    
       public final void setEmpty(boolean value) {
          this.size *= 2;
       }
    }
    

    Clearly we can see that the java class has only getter and setter functions for isEmpty, and there is no field declared for it. Similarly in Kotlin, there is no backing field for property isEmpty, since the property doesn't depend on that field at all. Thus no backing field.


    Now let us remove the custom getter and setter of isEmpty property.

    class DummyClass {
        var size = 0;
        var isEmpty = false
    }
    

    And the Java equivalent of the above class is

    public final class DummyClass {
       private int size;
       private boolean isEmpty;
    
       public final int getSize() {
          return this.size;
       }
    
       public final void setSize(int var1) {
          this.size = var1;
       }
    
       public final boolean isEmpty() {
          return this.isEmpty;
       }
    
       public final void setEmpty(boolean var1) {
          this.isEmpty = var1;
       }
    }
    

    Here we see both the fields size and isEmpty. isEmpty is a backing field because the getter and setter for isEmpty property depend upon it.

提交回复
热议问题