Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is better approach of callback in Kotlin? Listener vs High-Order function [closed]

Tags:

android

kotlin

Please explain a use cases and pros and cons of each approach.

  1. Use of interface.

    fun doSomethingWithCallback(callback: Callback) {
        // Do something
        callback.call()
    }
    
  2. Use of high-order function.

    fun doSomethingWithCallback(callback: () -> Unit) {
        // Do something
        callback()
    }
    
like image 878
Demigod Avatar asked May 25 '18 12:05

Demigod


People also ask

Is higher-order function same as callback function?

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.

Why are higher-order functions useful in Kotlin?

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.

Are listeners callbacks?

They are the same! Two ways of naming an interface. In general, Listener is also a callback and VICE VERSA!


2 Answers

Option 1

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.

Option 2

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.

Option 3

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.

like image 116
jivimberg Avatar answered Sep 26 '22 23:09

jivimberg


  1. You can use with a lambda :

       doSomethingWithCallback { // do whatever you want }
    
  2. 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
    }
like image 27
ininmm Avatar answered Sep 25 '22 23:09

ininmm