Kotlin泛型通配符扩展

时间:2017-03-05 16:51:29

标签: generics kotlin

所以,我一直在尝试在Kotlin中实现一些Java,并且我遇到了将参数传递给通配符泛型类方法的挑战。 例如:

interface A
class B<in T : A> {
    fun pass(e: T) {
    /* do something */
    }
 }

class C {
    private val things = mutableListOf<B<*>>()
    fun test(e: A) {
        things.get(0)?.pass(e) // This doesn't work, since wildcard B generic wants Nothing, since Nothing can be safely passed to it.
         // but, I know that `e` is passable to `pass` method, since
         // its an impl of A
    }
 }

可以在Java中实现这一点,但它是否在Kotlin中?如果是这样,我该怎么做?

1 个答案:

答案 0 :(得分:0)

如果你已经知道T必须扩展A,你可以在&#39; C.things&#39;中指定初始化。

private val things = mutableListOf<B<A>>()