[英]How to translate Kotlin Nothing to Java?
I have a class that is MyClass<T>
我有一个类是MyClass<T>
I need to subclass it to MySubclass<Nothing>
我需要将其子类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?但有时我需要向 Java 函数发送MyClass
引用,该函数又可以接收MySubclass
,我如何声明它以使其兼容?
Or should I simply use void receiveClass(aClass: MyClass<*>)
?或者我应该简单地使用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.这两种变体在运行时都可以工作并且是等效的,区别在于您是否需要receiveClass
的类型信息<E>
以确保编译时的类型安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.