且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Kotlin编写的界面中使用默认方法的Java 8功能

更新时间: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目标字节码1.8或更高版本:-jvm-target 1.8
  • 启用JVM默认方法:-Xjvm-default=enable(请参见上面的链接查看其他可用的选项值)
  • JVM target bytecode version 1.8 or higher: -jvm-target 1.8
  • enable JVM default methods: -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 {
}