覆盖类kotlin中的变量的get方法?

时间:2020-09-23 09:05:12

标签: java android kotlin data-class

我在Java中有一个模型类,后来在kotlin中将其转换为数据类

public class VideoAssets implements Serializable {

@SerializedName("type")
@Expose
String type;

@SerializedName("mpeg")
@Expose
List<Mpeg> mpeg = null;

@SerializedName("hls")
@Expose
String hls;

@SerializedName("widevine")
@Expose
WideVine wideVine;

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public List<Mpeg> getMpeg() {
    return mpeg;
}

public void setMpeg(List<Mpeg> mpeg) {
    this.mpeg = mpeg;
}

public String getHls() {
    hls = Macros.INSTANCE.replaceURl(hls);
    return hls;
}

public void setHls(String hls) {
    this.hls = hls;
}

public WideVine getWideVine() {
    return wideVine;
}

public void setWideVine(WideVine wideVine) {
    this.wideVine = wideVine;
}
}

如您所见,我想在检索变量hls时更改它的值。

我创建了如下的数据类

data class VideoAssets(@SerializedName("mpeg") @Expose
                   var mpeg: List<Mpeg> = emptyList(),
                   @SerializedName("hls")
                   @Expose
                   var hls: String,
                   @SerializedName("widevine")
                   @Expose
                   val wideVine: WideVine? = null) : Serializable

我在这里苦苦挣扎,因为我应该如何更新数据类的get方法。 经过Override getter for Kotlin data class的搜索并获得参考后 我什至创建了一个似乎无法正常工作的非数据类

class VideoAssets(@SerializedName("mpeg") @Expose
              var mpeg: List<Mpeg> = emptyList(),
              @SerializedName("hls")
              @Expose
              val hlsUrl: String? = null,
              @SerializedName("widevine")
              @Expose
              val wideVine: WideVine? = null) : Serializable {
val hls: String? = hlsUrl
    get() = field?.let { Macros.replaceURl(it) }

}

每当我尝试检索videoAssets.getHls()时,它都将返回null,而应返回新值。对象videoAssets.gethlsUrl()具有值,但`videoAssets.getHls()'始终为null。

有人可以指出我所缺少的东西吗?

1 个答案:

答案 0 :(得分:0)

这是您的代码:

val hls: String? = hlsUrl
    get() = field?.let { Macros.replaceURl(it) }

因此,这是在创建一个名为hls的属性,并为其提供一个名为field的后备字段(变量)。最初将其设置为hlsUrl传递给构造函数的任何值(可能为null)。

getter代码使用field的值,如果不为空,则 调用该replaceURl函数并返回结果,否则返回null。 / p>

因此,如果将hlsUrl设置为null,则field将始终为null,而hls getter将始终返回null。即使稍后再更新hlsUrl(我假设您正在这样做,如果我将值传递给构造函数,代码对我来说也可以正常运行)field的值在初始化时是固定的。

您的Java代码也以不同的方式运行-当它获得新值hls时,它将存储该值并将其用于下一个get的函数调用中。您永远不会更改field的值,因此您的Kotlin代码每次都使用初始值。

从技术上讲,您不需要后备字段,因为您始终可以有效地调用hlsUrl?.let { Macros.replaceURl(it) }。在这种情况下,您可以将hlsUrl设为var并对其进行更新,或者可以在hls新值{p> 1}中将设置器添加到get属性中并设置背景字段

Here's the Kotlin page on properties,以防万一您没看!