简体   繁体   中英

How to translate Kotlin Nothing to Java?

I have a class that is MyClass<T>

I need to subclass it to MySubclass<Nothing>

But sometimes I need to send a MyClass reference to a Java function, which in turn can receive MySubclass , How can I declare it so that it is compatible?

Or should I simply use void receiveClass(aClass: MyClass<*>) ?

If I understood your question correctly, you can do:

// Kotlin:
open class MyClass<T>
class MySubclass : MyClass<Nothing>()
// Java:
static <E> void receiveClass(MyClass<E> c) {
}

static void receiveClass1(MyClass<?> c) {
}
// Kotlin:
@JvmStatic
fun main(args: Array<String>) {
  receiveClass(MySubclass())
  receiveClass1(MySubclass())
}

Both variants will work and are equivalent during runtime, the difference is whether you need the type information <E> inside the receiveClass for type safety in compile time.

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