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中呢? 如果是这样,我该怎么做?

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

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