Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Kotlin function with Lambda parameters in Java

Tags:

java

kotlin

How do I call Kotlin functions with lambdas in the parameter from a Java class.

Example

fun getToken(
        tokenUrl: String,
        onSuccess: (String) -> Unit,
        onError: (Error) -> Unit
    ): Provider {
        //Implementation
    }
like image 905
Alan Avatar asked Mar 04 '26 08:03

Alan


2 Answers

You can do this

    value.getToken("url",
    new Function1<String, Unit>() {
        @Override
        public Unit invoke(String s) {
            /* TODO */
            return Unit.INSTANCE;
        }
    }, new Function1<Throwable, Unit>() {
        @Override
        public Unit invoke(Throwable throwable) {
            /* TODO */
            return Unit.INSTANCE;
        }
    });
like image 59
Francesc Avatar answered Mar 05 '26 22:03

Francesc


You can call it with normal Java 8 lambdas, since Kotlin is actually using a single-method interface on the backend.

myFoo.getToken(tokenUrl, successString -> { ... }, error -> { ... });
like image 23
Louis Wasserman Avatar answered Mar 05 '26 21:03

Louis Wasserman