Use of constructor parameter modifier (var val) in Kotlin inheritance relationship

I just came into contact with Kt recently. When I used Kt yesterday, I encountered a problem with the use of val var in the constructor. Although the function was completed yesterday, it was still a little confusing. introduce.

Requirement: There is a Child class that is a data class, inheriting a parent class Parent, so that some parameters of the parent are shared in Child. This is easy to implement in java, but in Kt, due to the need to use the data class (later required do gson conversion), encountered a problem in processing the constructor .

 

1. At the beginning, I defined Parent to be the data class, but the data class is final, so it cannot be inherited by children, failure

2. That can only define Parent as class, Child as data

open class Parent(weight: Int, height: Int)
data class Child(var grade: Int, var weight: Int, var height: Int) : Parent(weight, height)

Here's the problem. Why doesn't the father have a var val and the child has a var val? Can it be removed? 

Of course, data cannot be removed from var/val. After removing it, it will report data class must have only property (var/val) parameters

Can Parent add var or val? Let's see by converting to java code:

1. Base constructor has no var val

open class Base(num: Int)

java

public class Base {
   public Base(int num) {
   }
}

Base constructor has val

public class Base {
   private final int num;

   public final int getNum() {
      return this.num;
   }

   public Base(int num) {
      this.num = num;
   }
}

Base constructor has var 

public class Base {
   private int num;

   public final int getNum() {
      return this.num;
   }

   public final void setNum (int var1) {
      this.num = var1;
   }

   public Base(int num) {
      this.num = num;
   }
}

 

In fact, var is actually adding getter and setter methods to the code when compiling, val is read-only, only the getter method is added

Without var, val will not generate any getters and setters.

These getter setters are final.

If there is a getter setter in Base, and the subclass data class also has the same field, the getter setter will conflict.

 

Summarize:

1.val var is the getter.setter that participates in the final

2. When KT encounters a problem, it can quickly find the answer by converting it to java code

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324897259&siteId=291194637