Kotlin型错配。预期任何收到的MyObject

时间:2017-12-08 22:00:16

标签: android kotlin

我正在制作一个可观察LiveData个对象的列表,它应该包含Resource个对象(https://developer.android.com/topic/libraries/architecture/guide.html#addendum)。我不关心Resource对象包含哪种类型的数据。

abstract class LiveResources : LiveData<Resource<Any>>() {
  private val mediatorLiveData = MediatorLiveData<Resource<Any>>()
  protected val resources = HashSet<LiveData<Resource<Any>>>()

  fun addResource(source: LiveData<Resource<Any>>) {
    resources.add(source)
    mediatorLiveData.addSource(source, resourceObserver)
  }

  fun removeResource(source: LiveData<Resource<Any>>) {
    resources.remove(source)
    mediatorLiveData.removeSource(source)
  }

  private val resourceObserver = Observer<Resource<Any>> {
    onSourceChange()
  }

  abstract fun onSourceChange()
}

不幸的是,当我尝试将LiveResources.addResource()LiveData<Resource<List<String>>>一起使用时,我的IDE中出现了TypeMismatch错误,并说LiveData<Resource<Any>>是预期的。

3 个答案:

答案 0 :(得分:1)

您的资源(和/或LiveData)类应使用通用协方差定义,以使其工作。像这样:

class Resource<out T> // <- out marks generic type as covariant

答案 1 :(得分:0)

Haven没有尝试过,但我认为这样可行

public abstract class VBO { public static TexVBO create(double vertices[], double texCoords[], Texture tex) { int vertexId, textureId; DoubleBuffer Bvertex, Btexture; vertexId = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, vertexId); glBufferData(GL_ARRAY_BUFFER, Bvertex = dBuf(vertices), GL_STATIC_DRAW); textureId = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, textureId); glBufferData(GL_ARRAY_BUFFER, Btexture = dBuf(texCoords), GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); return new TexVBO( vertexId, textureId, vertices.length / 3, texCoords.length / 2, Bvertex, Btexture, tex.getTextureId(), 7); } public abstract void draw(); public abstract void delete(); private static DoubleBuffer dBuf(double d[]) { DoubleBuffer buf = BufferUtils.createDoubleBuffer(d.length); buf.put(d); buf.flip(); return buf; } }

答案 2 :(得分:0)

您应该将类​​格式化为接受Resource<T>,即LiveData<Resource<T>>Any是传递的任何对象的协方差,但我认为你并不是想实现这一目标。

另一个友好的建议是,您不需要在MediatorLiveData之上添加另一个抽象,这完全与您实现的相同。