更新时间:2022-12-04 16:52:00
在Kotlin中,带有主体的接口方法默认情况下编译如下:
In Kotlin, interface methods with bodies are by default compiled as following:
// kotlin
interface B {
fun optional() { println("B optional body") }
}
大致编译为:
public interface B {
void optional();
public static final class DefaultImpls {
public static void optional(B $this) {
System.out.println("B optional body");
}
}
}
然后,在实现此接口的Kotlin类中,编译器自动为optional
方法添加覆盖并在其中调用B.DefaultImpls.optional(this)
.
Then, in Kotlin classes implementing this interface, the compiler adds an override for optional
method automatically and calls B.DefaultImpls.optional(this)
there.
public final class KA implements B {
public void optional() {
B.DefaultImpls.optional(this);
}
}
但是如果您想用Java实现此接口并避免必须重写optional
方法并手动调用B.DefaultImpls
怎么办?在这种情况下,您可以使用实验性@JvmDefault
功能.
But what if you want to implement this interface in Java and avoid having to override optional
method and calling B.DefaultImpls
manually? In that case you can use the experimental @JvmDefault
feature.
首先,您需要启用几个编译器选项:
First, you need to enable a couple of compiler options:
-jvm-target 1.8
-Xjvm-default=enable
(请参见上面的链接查看其他可用的选项值)-jvm-target 1.8
-Xjvm-default=enable
(see the other available option values by the link above)然后,用@JvmDefault
批注注释optional
方法:
Then, you annotate optional
method with @JvmDefault
annotation:
// kotlin
interface B {
@JvmDefault
fun optional() { println("B optional body") }
}
它将被编译为
public interface B {
@JvmDefault
default void optional() {
System.out.println("B optional body");
}
}
现在该接口的Java实现变为:
And now the Java implementation of this interface becomes just:
public final class A implements B {
}