【问题标题】:Kotlin data class with SerializedName annotations variables in init block初始化块中带有 SerializedName 注释变量的 Kotlin 数据类
【发布时间】:2019-01-14 11:19:01
【问题描述】:

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

问题是,在 init 块中,对象仍未初始化,并且 nick、images 等变量为空。我应该在哪里写 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
    }
}

【问题讨论】:

    标签: android kotlin gson


    【解决方案1】:

    上面的内容对我使用 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 代码。

    【讨论】:

      猜你喜欢
      • 2021-07-08
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      相关资源
      最近更新 更多