在Kotlin中,对于Parcelable类中的CREATOR来说,正确的方法是什么

时间:2018-09-28 16:13:52

标签: kotlin parcelable kotlin-companion

与kotlin一起,拥有一个Data类可以实现Parcelable

似乎在同伴中有两种定义CREATOR: Parcelable的方式:

1。

data class Data (
    @SerializedName("id")
    val id: String?,
    @SerializedName("blob")
    val blob: String?
) : Parcelable {

... ...
companion object CREATOR : Parcelable.Creator<Data> {
    override fun createFromParcel(parcel: Parcel): Data {
        return Data(parcel)
    }

    override fun newArray(size: Int): Array<Data?> {
        return arrayOfNulls(size)
    }
}

}

2

data class Data (
    @SerializedName("id")
    val id: String?,
    @SerializedName("blob")
    val blob: String?
) : Parcelable {

... ...

companion object {

    @JvmField val CREATOR: Parcelable.Creator<Data> = object : Parcelable.Creator<Data> {
        override fun createFromParcel(parcel: Parcel): Data {
            return Data(parcel)
        }

        override fun newArray(size: Int): Array<Data?> {
            return arrayOfNulls(size)
        }
    }

}

}

相应的Java反编译代码为

1

   @JvmField
   @NotNull
   public static final Creator CREATOR = (Creator)(new Creator() {
   @NotNull
   public Data createFromParcel(@NotNull Parcel parcel) {
     Intrinsics.checkParameterIsNotNull(parcel, "parcel");
     return new Data(parcel, (DefaultConstructorMarker)null);
  }

  // $FF: synthetic method
  // $FF: bridge method
  public Object createFromParcel(Parcel var1) {
     return this.createFromParcel(var1);
  }

  @NotNull
  public Data[] newArray(int size) {
     return new Data[size];
  }

  // $FF: synthetic method
  // $FF: bridge method
  public Object[] newArray(int var1) {
     return this.newArray(var1);
  }
});

2

  public static final Data.CREATOR CREATOR = new Data.CREATOR((DefaultConstructorMarker)null);

  public static final class CREATOR implements Creator {
  @NotNull
  public Data createFromParcel(@NotNull Parcel parcel) {
     Intrinsics.checkParameterIsNotNull(parcel, "parcel");
     return new Data(parcel);
  }

  // $FF: synthetic method
  // $FF: bridge method
  public Object createFromParcel(Parcel var1) {
     return this.createFromParcel(var1);
  }

  @NotNull
  public Data[] newArray(int size) {
     return new Data[size];
  }

  // $FF: synthetic method
  // $FF: bridge method
  public Object[] newArray(int var1) {
     return this.newArray(var1);
  }

  private CREATOR() {
  }

  // $FF: synthetic method
  public CREATOR(DefaultConstructorMarker $constructor_marker) {
     this();
  }
}

并使用kotlin从包裹中获取List<Data>

parcel.createTypedArrayList(Data.CREATOR)

在Java中可能是:

List list = (List)(new ArrayList());
parcel.readTypedList(list, (Creator)Data.CREATOR);

kotlin中的两个CREATOR都很好。

有什么区别,哪个更好用?

0 个答案:

没有答案