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

Barry Fruitman :

Can I call this Kotlin method from Java?

fun foo(() -> Unit)

If so, what's the syntax?

Todd :

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;
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=87164&siteId=1