Please explain a use cases and pros and cons of each approach.
Use of interface.
fun doSomethingWithCallback(callback: Callback) {
// Do something
callback.call()
}
Use of high-order function.
fun doSomethingWithCallback(callback: () -> Unit) {
// Do something
callback()
}
A higher-order function is a function that takes another function(s) as an argument(s) and/or returns a function to its callers. A callback function is a function that is passed to another function with the expectation that the other function will call it.
High-order functions and lambdas Kotlin functions are first-class, which means they can be stored in variables and data structures, and can be passed as arguments to and returned from other higher-order functions. You can perform any operations on functions that are possible for other non-function values.
They are the same! Two ways of naming an interface. In general, Listener is also a callback and VICE VERSA!
With option 1 you're not able to call it passing a lambda. For example this does not compile:
doSomethingWithCallback1 { print("helloWorld") }
Interestingly if the same method were defined in Java:
void doSomethingWithJavaCallback(JavaCallback callback) {
// Do something
callback.call();
}
Then you can call it using a lambda from Kotlin. This is because Kotlin only does SAM-conversion for functions defined in Java.
In contrast if you go with option 2 you do get to call it using a lambda. And it will work both when calling it from Kotlin and from Java.
As mentioned in the comments a third option is using a type alias like this:
typealias Callback = () -> Unit
fun doSomethingWithCallback5(callback: Callback) {
// Do something
callback()
}
You get to keep the type in the function signature and use lambdas on the call site.
You can use with a lambda :
doSomethingWithCallback { // do whatever you want }
I usually use lambda function by this one:
var doSomething: ((Any) -> Unit)? = null
and invoke callback:
doSomething?.invoke(any)
finally as same as listener:
youClass.doSomething = { any ->
// this is callback
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With