12

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
    }
1
  • A lambda is just a closure in Kotlin Commented May 29, 2019 at 21:05

3 Answers 3

28

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;
        }
    });
Sign up to request clarification or add additional context in comments.

3 Comments

Don't forget to add return Unit.INSTANCE; in the invoke method.
This comment should be part if the answer. @Francesc can you please update your answer to include the comment? Thanks
While this answer is correct, I would much prefer Louis's answer.
9

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

1 Comment

Thanks! Unfortunately my project is not set to Java 8.
-1

This is for calling it within Kotlin, the question was edited to say "from Java" after I provided my answer. Leaving it here anyway in hope that it is useful.

You can call it like this

fun test() {

    getToken("asdf", { print(it) }, { println(it) })

    getToken("asdf", { print(it) }) { err -> println(err) }

    getToken("asdf", ::println, ::println)

    getToken("asdf", ::println) { println(it) }
}

4 Comments

I know how to call it within Kotlin. I want to call the function from a Java class.
Your original question was edited. Before it didn't say from Java. I think the downvotes I received were unnecessary.
it did, but it was only in the title. I added it in the body after you answered it incorrectly for additional clarification. Call Kotlin function with Lambda parameters in Java. I think your downvote of my question is unnecessary.
I didn't downvote your question. Also I assumed other people downvoted my answer since you had the full context and would understand why my answer was seemingly incorrect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.