Kotlin minimalist tutorial (9) - data classes

Keywords: Java

Data class is a very powerful class, which can avoid repeatedly creating the template code of POJO used to save state but operate very simple in Java. They usually only provide simple getter s and setter s for accessing their properties

Defining a new data class is very simple, such as

data class Point(val x: Int, val y: Int)

By default, the data class overloads several methods for developers, including getter, setter (required to be var), componentN(), copy(), toString(), hashCode(), equals(), etc
You can use IDEA to decompile and view the Java implementation of the Point class, and understand its internal implementation

public final class Point {
   private final int x;
   private final int y;

   public final int getX() {
      return this.x;
   }

   public final int getY() {
      return this.y;
   }

   public Point(int x, int y) {
      this.x = x;
      this.y = y;
   }

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

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

   @NotNull
   public final Point copy(int x, int y) {
      return new Point(x, y);
   }

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

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

      return var0.copy(var1, var2);
   }

   public String toString() {
      return "Point(x=" + this.x + ", y=" + this.y + ")";
   }

   public int hashCode() {
      return this.x * 31 + this.y;
   }

   public boolean equals(Object var1) {
      if (this != var1) {
         if (var1 instanceof Point) {
            Point var2 = (Point)var1;
            if (this.x == var2.x && this.y == var2.y) {
               return true;
            }
         }

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

Through data classes, many common operations are simplified, which can be easily performed: formatting output variable values, mapping objects to variables, comparing equality between variables, copying variables, etc

fun main(args: Array<String>) {
    val point1 = Point(10, 20)
    val point2 = Point(10, 20)
    println("point1 toString() : $point1")
    println("point2 toString() : $point2")

    println()
    val (x, y) = point1
    println("point1 x is $x,point1 y is $y")

    println()
    //In kotlin, "= =" is equivalent to Java's equals method
    //And "==== is equivalent to Java's" = = "method
    println("point1 == point2 : ${point1 == point2}")
    println("point1 === point2 : ${point1 === point2}")

    println()
    val point3 = point1.copy(y = 30)
    println("point3 toString() : $point3")
}

Posted by Coldman on Fri, 03 Apr 2020 01:18:24 -0700