Kotlin抽象方法与身体

bit*_*ale 2 interface abstract kotlin

如上面所提到这里:如果在一个接口函数没有身体它是默认的抽象.但是界面的功能与身体没有任何关系.

例:

interface MyInterface {
    fun foo() { print("Something") }
    fun bar()
}

fun main(args: Array<String>) {
    println(MyInterface::foo.javaMethod)
    println(MyInterface::bar.javaMethod)
}
Run Code Online (Sandbox Code Playgroud)

输出将是:

public abstract void MyInterface.foo()
public abstract void MyInterface.bar()
Run Code Online (Sandbox Code Playgroud)

怎么可能,定义体的方法是抽象的?

zsm*_*b13 8

这与Kotlin接口中的默认方法的实现方式有关.界面中的foobar方法确实都是抽象的.

但是,界面内部有一个内部类,看起来像这样(简化):

public interface MyInterface {
   void foo();
   void bar();

   public static final class DefaultImpls {
      public static void foo() {
         System.out.print("Something");
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

此类是包含您在接口内为主体提供的任何函数的默认实现的类.

然后,如果您创建一个实现此接口的类,并且您不重写该foo方法:

class MyClass: MyInterface {
    override fun bar() {
        println("MyClass")
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你会自动生成一个,它只调用里面的实现DefaultImpls:

public final class MyClass implements MyInterface {
   public void bar() {
      System.out.println("MyClass");
   }
   public void foo() {
      MyInterface.DefaultImpls.foo();
   }
}
Run Code Online (Sandbox Code Playgroud)

您可以使用Kotlin插件附带的字节码查看器(Tools -> Kotlin -> Show Kotlin Bytecode,然后Decompile选项)找到所有这些细节.