Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a lambda from Java to a Kotlin method?

Can I call this Kotlin method from Java?

fun foo(() -> Unit)

If so, what's the syntax?

like image 657
Barry Fruitman Avatar asked Dec 08 '22 12:12

Barry Fruitman


2 Answers

You need to create instance of Function0:

foo(new Function0<Unit>() {
    @Override
    public Unit invoke() {
        // Here should be a code you need
        return null;
    }
});

or if you use Java 8 it can be simplified

foo(() -> {
    // Here should be a code you need
    return null;
});
like image 189
Andrew Churilo Avatar answered Jan 27 '23 19:01

Andrew Churilo


You can call this but need to be careful of the return types. If your Kotlin function returns a Unit, Java will either need to return Unit or null, because void is not quite the same as Unit.

My example that worked:

foo(() -> {
    System.out.println("Hi");
    return null;
});

Or, if you want to be really explicit about Unit...

foo(() -> {
    System.out.println("Hi");
    return Unit.INSTANCE;
});
like image 41
Todd Avatar answered Jan 27 '23 19:01

Todd