something about SAM

kotlin code:

fun go(r: Runnable) = r.run()

//fun fGo(f: () -> Unit) = go(f)

fun main() {
    val g: () -> Unit = { println("what")}
    go(g)
}

equivalent java code:

package temp;

import kotlin.jvm.functions.Function0;
import kotlin.jvm.internal.Lambda;

/**
 * @author Xin Wang
 * @date 5/28/2021
 */

public class Temp2Kt {
    public final static void go(Runnable r) {
        r.run();
    }

    public static void main(String[] args) {


        final class Temp2Kt$sam$java_lang_Runnable$0 implements Runnable {
            private final Function0 function;

            public Temp2Kt$sam$java_lang_Runnable$0(Function0 function) {
                super();
                this.function = function;
            }

            @Override
            public void run() {
                final Object result = function.invoke();
            }
        }

        //////////////main
        final Temp2Kt$main$g$1 instance = Temp2Kt$main$g$1.INSTANCE;
        final Temp2Kt$sam$java_lang_Runnable$0 runnable = new Temp2Kt$sam$java_lang_Runnable$0(instance);
        go(runnable);
    }
}

// this is an inner class of Temp2Kt
final class Temp2Kt$main$g$1 extends Lambda implements Function0 {

    public final static Temp2Kt$main$g$1 INSTANCE = new Temp2Kt$main$g$1();

    public Temp2Kt$main$g$1() {
        super(0);
    }

    @Override
    public Object invoke() {
        this.invoke1();
        return null;
    }

    public final void invoke1() {
        System.out.println("what");
    }
}



上一篇:字母图形


下一篇:OO第三单元总结