Generics Kotlin泛型通配符,带扩展

Generics Kotlin泛型通配符,带扩展,generics,kotlin,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.

所以,我一直在尝试在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
    }
 }
接口A
B类{
趣味通行证(e:T){
/*做点什么*/
}
}
C类{
private val things=mutableListOf()
趣味测验(e:A){
things.get(0)?.pass(e)//这不起作用,因为通配符B generic不需要任何东西,因为任何东西都不能安全地传递给它。
//但是,我知道'e'可以通过'pass'方法,因为
//这是一个简单的例子
}
}

在Java中实现这一点是可能的,但它是在Kotlin中实现的吗?如果是这样的话,我应该怎么做?

如果您已经知道T必须扩展A,那么可以在“C.things”初始化中指定它

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

您将如何在Java中实现它?你不知道B的泛型类型是什么,所以你不知道你传递的
e
是否是正确的类型。我确实找到了类似于
ArrayList
的东西,但没有指定
t
的泛型,它确实按照预期编译和工作。虽然,我不知道它是如何工作的。是的,但它使用的是原始类型,因此不是类型安全的。啊,由于Kotlin的泛型是类型安全的,这是不可能的?好吧,不,不是这样的。Java泛型也是类型安全的。但是如果使用ArrayList,就不会使用B作为泛型类型。您将其用作aw类型,实际上是在告诉编译器:这里忘记类型安全。