【问题标题】:Can MutableLiveData have a subclass as it's type?MutableLiveData 可以有一个子类作为它的类型吗?
【发布时间】:2020-05-15 19:12:44
【问题描述】:

当参数为MutableLiveData<Superclass> 时,我无法将MutableLiveData<Subclass> 作为参数传递。问题是我的应用程序无法构建并且我收到:DataBinderMapperImpl 错误:找不到符号。

这行得通:

fun display(list: List<SuperClass>)

打电话时instance.display(subClassList)

这不是:

fun display(liveData: MutableLiveData<Superclass>)

打电话给instance.display(subClassLiveData)时。

澄清一下,如果不是 LiveData,我可以将子类作为参数传递。但如果是 LiveData,我的应用将无法构建。

【问题讨论】:

    标签: android kotlin inheritance mutablelivedata


    【解决方案1】:

    当您的函数采用的参数的泛型类型不是用inout 缩小时,您不能传递除该确切类型之外的任何东西。

    List 和 LiveData 已经定义了 out 类型(协变),因此 List<Subtype> 符合 List<Supertype>LiveData<Subtype> 符合 LiveData<Supertype> 的条件。

    但是这些类的可变变体(MutableList 和 MutableLiveData)具有更改其中内容的方法,因此它们的类型必须能够进出。您不能允许超类型或子类型,因为它会在一个方向上破坏功能。

    如果你这样定义你的函数:

    fun display(list: MutableLiveData<out SuperClass>)
    

    那么您就可以将MutableLiveData&lt;Subclass&gt; 传递给它。您将无法从display 函数内部调用setValue

    【讨论】:

      猜你喜欢
      • 2018-03-30
      • 2019-12-07
      • 2014-05-25
      • 1970-01-01
      • 1970-01-01
      • 2015-06-15
      • 2015-10-07
      • 2013-12-09
      • 1970-01-01
      相关资源
      最近更新 更多