0

使用 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();
  }
}

List<Data>并且可以使用 kotlin从包裹中获取一个:

parcel.createTypedArrayList(Data.CREATOR)

在java中它可能是:

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

似乎在 kotlin 中,同伴中的两个 CREATOR 都很好。

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

4

0 回答 0