如何在Kotlin编写的界面中使用默认方法的Java 8功能 [英] How to use Java 8 feature of default method in interface written in Kotlin

查看:144
本文介绍了如何在Kotlin编写的界面中使用默认方法的Java 8功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有一个类A,在Kotlin中有一个接口B.

I have a class A in java and interface B in Kotlin.

// kotlin
interface B {
    fun optional()
}

// java
class A implements B {
}

我想在Kotlin接口(B)中编写默认方法(Java 8功能),并希望在A类中实现它. 我该如何实现?

I want to write the default method (Java 8 feature) in Kotlin interface (B) and want to implement it in the class A. How can I achieve it?

谢谢.

推荐答案

在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 {
}

这篇关于如何在Kotlin编写的界面中使用默认方法的Java 8功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆