Kotlin-数据类

声明一个数据类

data class DataClass(var name: String,var age: Int)

简单的声明就拥有了
Getter Setter toString() 重写的hashCode() 重写的equals()

看看 Java 的实现

public final class DataClass {
   @NotNull
   private String name;
   private int age;

   @NotNull
   public final String getName() {
      return this.name;
   }

   public final void setName(@NotNull String var1) {
      Intrinsics.checkNotNullParameter(var1, "");
      this.name = var1;
   }

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

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

   public DataClass(@NotNull String name, int age) {
      Intrinsics.checkNotNullParameter(name, "name");
      super();
      this.name = name;
      this.age = age;
   }

   @NotNull
   public final String component1() {
      return this.name;
   }

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

   @NotNull
   public final DataClass copy(@NotNull String name, int age) {
      Intrinsics.checkNotNullParameter(name, "name");
      return new DataClass(name, age);
   }

   // $FF: synthetic method
   public static DataClass copy$default(DataClass var0, String var1, int var2, int var3, Object var4) {
      if ((var3 & 1) != 0) {
         var1 = var0.name;
      }

      if ((var3 & 2) != 0) {
         var2 = var0.age;
      }

      return var0.copy(var1, var2);
   }

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

   public int hashCode() {
      String var10000 = this.name;
      return (var10000 != null ? var10000.hashCode() : 0) * 31 + Integer.hashCode(this.age);
   }

   public boolean equals(@Nullable Object var1) {
      if (this != var1) {
         if (var1 instanceof DataClass) {
            DataClass var2 = (DataClass)var1;
            if (Intrinsics.areEqual(this.name, var2.name) && this.age == var2.age) {
               return true;
            }
         }

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

data class 可以被继承么?

不行,如果想复用只能把基础类,换成 class

equlas 默认会实现所有对象

如需比较对象相等只用其中某些参数,需要重写 equlas 和 hashcode

你可能感兴趣的:(kotlin,java,开发语言)