美文网首页
关于Kotlin data类

关于Kotlin data类

作者: 请输入妮称 | 来源:发表于2017-08-10 19:25 被阅读0次

    由于kotlin和java一样都是运行在jvm虚拟机上,所以最终生成的都是遵循jvm规范的字节码,因此可以通过反编译kotlin生成的字节码为java代码来学习kotlin的原理。

    1.data类的写法

    ```

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

    ```

    2.反编译成java代码后自动生成了变量的get、set方法,equals方法,copy方法,component1(),component2(),hashCode()方法,如下:

    ```

    public final class People {

    @NotNull

    private String name;

    private int age;

    @NotNull

    public final String getName() {

    return this.name;

    }

    public final void setName(@NotNull String var1) {

    Intrinsics.checkParameterIsNotNull(var1,"");

    this.name = var1;

    }

    public final int getAge() {

    return this.age;

    }

    public final void setAge(intvar1) {

    this.age = var1;

    }

    public People(@NotNull String name, int age) {

    Intrinsics.checkParameterIsNotNull(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 People copy(@NotNull String name, int age) {

    Intrinsics.checkParameterIsNotNull(name,"name");

    return new People(name,age);

    }

    // $FF: synthetic method

    // $FF: bridge method

    @NotNull

    public static People copy$default(People 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);

    }

    public String toString() {

    return "People(name="+this.name +", age="+this.age +")";

    }

    public int hashCode() {

    return (this.name !=null?this.name.hashCode():0) *31+this.age;

    }

    public boolean equals(Object var1) {

    if(this!= var1) {

    if(var1 instanceof People) {

    People var2 = (People)var1;

    if(Intrinsics.areEqual(this.name,var2.name) &&this.age == var2.age) {

    return true;

    }

    }

    return false;

    }else{

    return true;

    }

    }

    }

    ```

    3.如果变量是val修饰,如data class People(var name:String,val age:Int),则只会为age变量生成get方法。

    4.如果data类中需要定义常量,则常量的实际初始化阶段是在构造方法中,这点与java是不一样的

    kotlin代码:

    ```

    data class People(var name: String, var age: Int) {

    val female=1

    val male=2

    }

    ```

    反编译后的java代码(部分片段):

    ```

    private final int female;

    private final int male;

    @NotNull

    private String name;

    private int age;

    public People(@NotNull String name, int age) {

    super();

    this.name = name;

    this.age = age;

    this.female =1;

    this.male =2;

    }

    ```

    这点要尤其注意,因为在json的反序列化的过程中,如果调用的是无参构造方法(gson的实现),那么常量是没有进行过赋值的

    相关文章

      网友评论

          本文标题:关于Kotlin data类

          本文链接:https://www.haomeiwen.com/subject/dofkrxtx.html