Calling function types

Now that you know how to define a function type, let's see how we can make use of them.

Calling a function type is the same as calling a normal function. You put parentheses after the function variable or the argument that is a function type. Here's a function that simulates a long-running task and accepts two callback functions, one in the case of successful completion and one in the case of an error. Inside the function, you can see how we call the onFinished and onError function type arguments:

fun longRunningTask(onFinished: (Any) -> Unit, onError: (Throwable) -> Unit) {
try {
//something long running
onFinished("got result")
} catch (fail: Throwable) {
onError(fail)
}
}

All function types also have the invoke method (we'll see in the Calling function types from Java section why this is), which can also be used to call a function type, like this example shows:

fun longRunningTask(onFinished: (result: Any) -> Unit, onError: (fail: Throwable) -> Unit) {
try {
//something long running
onFinished.invoke("got result")
} catch (fail: Throwable)
{
onError.invoke(fail)
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.35.16