简体   繁体   中英

Java/Kotlin generic list incompatible types with wildcard

I have an abstract Java class with a concrete method that calls a method in the subclasses:

abstract class JavaSuperclass<T> {
    T doSomething() {
        ...
        return doSomethingInSubclass();
    }

    abstract T doSomethingInSubclass();
}

I have a Java subclass with its generic type set to a List:

class JavaSubclass extends JavaSuperclass<List<WhateverJava>> {
    List<WhateverJava> doSomethingInSubclass() {...}
}

And I have a Kotlin subclass:

class KotlinSubclass : JavaSuperclass<List<WhateverKotlin>> {
    override fun doSomethingInSubclass(): List<WhateverKotlin> {...}
}

( WhateverJava is a Java class, WhateverKotlin is a Kotlin data class.)

Then in a Java class I'm using both subclasses.

List<WhateverJava> listFromJava = javaSubclass.doSomething();
List<WhateverKotlin> listFromKotlin = kotlinSubclass.doSomething();

The line that calls the Java subclass compiles fine, but the one that calls the Kotlin subclass gives this error:

error: incompatible types: List<capture<? extends WhateverKotlin>> cannot be converted to List<WhateverKotlin>

Lists in Kotlin are covariant. So the Kotlin class translates to Java as:

class KotlinSubclass extends JavaSuperclass<List<? extends WhateverKotlin>>

Adding a @JvmSuppressWildcards annotation to the Kotlin class fixes it.

class KotlinSubclass : JavaSuperclass<@JvmSuppressWildcards List<WhateverKotlin>> {
    override fun doSomethingInSubclass(): List<WhateverKotlin> {...}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM