Kotlin 嵌套函数

2020-01-27  本文已影响0人  七零八落问号

百度了一下没有找到嵌套函数的本质,在这里做个记录

示例类和方法

class AClass {
    fun outer(): Unit {
        fun nesting(): Unit {}
        nesting()
    }
}

以上代码通过查看Bytecode,可以看到定义 nesting() 的行,对应

GETSTATIC com/jctv/kotlintest/AClass$outer$1.INSTANCE : Lcom/jctv/kotlintest/AClass$outer$1;

而调用 nesting() 的行则对应

INVOKEVIRTUAL com/jctv/kotlintest/AClass$outer$1.invoke ()V

然后往下,发现对应的生成的一个类

final class com/jctv/kotlintest/AClass$outer$1
        extends kotlin/jvm/internal/Lambda
        implements kotlin/jvm/functions/Function0 {
  
    public final invoke()V
    public final static Lcom/jctv/kotlintest/AClass$outer$1; INSTANCE
}

事实上翻译成Java代码,大概则对应

public final class AClass {
    public final void outer() {
        AClass$outer$1.INSTANCE.invoke();
    }
}

final class AClass$outer$1 {
    public final static AClass$outer$1 INSTANCE;
    static{
        INSTANCE = new AClass$outer$1();
    }
    public final void invoke() {
    }
}

以上非直接翻译,有兴趣了解具体情况,可以自行查看Kotlin Bytecode

上一篇 下一篇

猜你喜欢

热点阅读