在初始化块中带有Seri​​alizedName注释变量的Kotlin数据类

时间:2019-01-14 11:19:01

标签: android kotlin gson

我下面有一个数据类。使用协程并将结果转换为带有gson的UserItem对象。

问题是,在init块中,对象仍未初始化,并且缺口,图像等变量为空。我应该在哪里在init块中编写代码?

data class UserItem(
    @SerializedName("username") val nick: String = "",
    @SerializedName("full_name") val fullName: String = 0,
    @SerializedName("info") val bio: String = "",
    @SerializedName("images") val images: List<String> = 
arrayListOf(),
    var imageType: ImageType = ImageType.NO_PHOTO
){
    companion object {
        @JvmStatic
        val DISPLAY_TYPE_USER = 0
        @JvmStatic
        val DISPLAY_TYPE_INFO = 1
    }

    enum class ImageType {
        NO_PHOTO, SINGLE_PHOTO, MULTIPLE_PHOTO
    }

    init {
        if (images.size == 1)
            imageType = ImageType.SINGLE_PHOTO
        else if (images.size > 1)
            imageType = ImageType.MULTIPLE_PHOTO
    }
}

1 个答案:

答案 0 :(得分:0)

使用kotlin 1.3.11进行细微的修改,上面的内容对我来说很好用-@SerializedName("full_name") val fullName: String = 0不能为整数,因此我将其更改为@SerializedName("full_name") val fullName: String = ""

实际上,运行此命令:

fun main(args: Array<String>) {
  println(UserItem().imageType)
  println(UserItem(images = listOf("foo")).imageType)
  println(UserItem(images = listOf("foo", "bar")).imageType)
}

输出:

NO_PHOTO
SINGLE_PHOTO
MULTIPLE_PHOTO

根据您的逻辑,这是正确的。反编译UserItem类时,可以看到以下构造函数:

public UserItem(@NotNull String nick, @NotNull String fullName, @NotNull String bio, @NotNull List images, @NotNull UserItem.ImageType imageType) {
  Intrinsics.checkParameterIsNotNull(nick, "nick");
  Intrinsics.checkParameterIsNotNull(fullName, "fullName");
  Intrinsics.checkParameterIsNotNull(bio, "bio");
  Intrinsics.checkParameterIsNotNull(images, "images");
  Intrinsics.checkParameterIsNotNull(imageType, "imageType");
  super();
  this.nick = nick;
  this.fullName = fullName;
  this.bio = bio;
  this.images = images;
  this.imageType = imageType;

  // This is what you have in the init block
  if (this.images.size() == 1) {
     this.imageType = UserItem.ImageType.SINGLE_PHOTO;
  } else if (this.images.size() > 1) {
     this.imageType = UserItem.ImageType.MULTIPLE_PHOTO;
  }
}

如您所见,init块在构造函数之后内联。也许我误解了这个问题?

PS:您可以通过执行“显示kotlin字节码”轻松地检查它们,这将弹出带有“反编译”按钮的窗口,该窗口将向您显示Java代码。