【Kotlin】Properties and Fields: Getters, Setters

We clarified comparing basic Kotlin classes with Java classes about properties and fields.

Property


// Kotlin
class Human {
  val age = 20
}


// Decompiled to Java
public final class Human {
   private final int age = 20;

   public final int getAge() {
      return this.age;
   }
}


// Kotlin
class Human {
  var age = 20
}


// Decompiled to Java
public final class Human {
   private int age = 20;

   public final int getAge() {
      return this.age;
   }

   public final void setAge(int var1) {
      this.age = var1;
   }
}

Backing field


// Kotlin
class Human {
  var age = 20
    set(value) {
      field = value
    }
}


// Decompiled to Java
public final class Human {
   private int age = 20;

   public final int getAge() {
      return this.age;
   }

   public final void setAge(int value) {
      this.age = value;
   }
}

Backing property


// Kotlin
class Human {
  private var _age: Int = 20
  val age: Int
    get() {
      return _age
    }

  fun setAge(value: Int) {
    _age = value
  }
}


// Decompiled to Java
public final class Human {
   private int _age = 20;

   public final int getAge() {
      return this._age;
   }

   public final void setAge(int value) {
      this._age = value;
   }
}

Data class


// Kotlin
data class Human(val age: Int = 20)


// Decompiled to Java
public final class Human {
   private final int age;

   public final int getAge() {
      return this.age;
   }

   public Human(int age) {
      this.age = age;
   }

   // $FF: synthetic method
   public Human(int var1, int var2, DefaultConstructorMarker var3) {
      if ((var2 & 1) != 0) {
         var1 = 20;
      }

      this(var1);
   }

   public Human() {
      this(0, 1, (DefaultConstructorMarker)null);
   }

   public final int component1() {
      return this.age;
   }

   @NotNull
   public final Human copy(int age) {
      return new Human(age);
   }

   // $FF: synthetic method
   @NotNull
   public static Human copy$default(Human var0, int var1, int var2, Object var3) {
      if ((var2 & 1) != 0) {
         var1 = var0.age;
      }

      return var0.copy(var1);
   }

   @NotNull
   public String toString() {
      return "Human(age=" + this.age + ")";
   }

   public int hashCode() {
      return this.age;
   }

   public boolean equals(@Nullable Object var1) {
      if (this != var1) {
         if (var1 instanceof Human) {
            Human var2 = (Human)var1;
            if (this.age == var2.age) {
               return true;
            }
         }

         return false;
      } else {
         return true;
      }
   }
}

Below you can see how to decompile your class on Android Studio!!


[Tools]

  |

[Kotlin]

  |

[Show Kotlin Bytecode]

  |

[Decompile]



👉【Kotlin】バッキング・フィールド/プロパティ
👉 Properties and Fields: Getters, Setters, const, lateinit - Kotlin Programming Language


関連ワード:  AndroidKotlin