Kotlin invoke supplied argument of type Unit

Viewed 1795

I struggle a bit with Kotlin right now.

In Java, what I'd do, is this:

public void doSomething(Consumer<String> onResult) {
    ...
    onResult.accept("Hello");
}

Now, from what I hear, in Kotlin I go about it like this:

fun doSomething(onResult: (message: String) -> Unit) {
    ...
}

How to pass on a value to onResult now?

fun doSomething(onResult: (message: String) -> Unit) {
    onResult.apply { "Hello" }
}

Or how to go about it?

3 Answers

Use normal method call. In doSomething method your parameter is a function . So you can pass value to incoming function with onResult("Hello");

fun mainMethod(m: String, functionAsParam: (m: String) -> Unit) {
    functionAsParam(m)
}

// my function to pass into the other
fun functionAsParam(m: String) {
    println("my message: $m")
}

Just an idea;

//Also you can call like this method 
fun tryMySolution() {
    mainMethod("hi", ::functionAsParam)
}

The onResult argument behaves like a normal function. You can just call it with onResult("Hello").

You could use the invoke method to invoke the parameter function or simply call the function:

fun main(args: Array<String>) {
    doSomething{ s -> println(s)}
    doSomething{ s -> println("You entered $s")}
}

fun doSomething(onResult: (message: String) -> Unit) {
    onResult("bla") // Invoke the passed function with a specific string
    // Note that onResult.invoke("bla") also does the same thing.
}

This will print:

bla
You entered bla
Related