SoFunction
Updated on 2025-04-05

Kotlin uses advanced functions to implement callback methods

lambda and higher-order functions

I learned lambda and higher-order functions before, and then listened to onClick events in android development is a very common function. The conventional implementation of kotlin is as follows:

   { view ->
    println("Clicked on thisID=${}ofview")
  }

Then, in development, we also need to write some code such as custom listening. At this time, if you still use Java's ideas to implement it, you will be a bit far away.

Java Idea Implementation

In Java, this is what we usually do

Define an interface
Define an interface type variable
Define a set method
Call the set method to set the implementation class of the interface

Using kotlin is as follows

class MyView{
  //Define an interface  interface IOnLabelCheckedListener {
    fun onLabelCheck(label: String)
  }
  //Define an interface type variable  private var onLabelChecked: IOnLabelCheckedListener? = null

  private fun initView(context: Context) {
     { radioGroup, i ->
        (<RadioButton>(i).())
    }
  }
  //Define a set method  fun setOnLabelCheckedListener(e: IOnLabelCheckedListener) {
     = e
  }
}

   // Call the set method and implement it through anonymous internal class    (object :  {
      override fun onLabelCheck(label: String) {

      }
    })

Problems to implement this

Of course it is too complicated. Moreover, I couldn't understand why the lambda expression cannot be passed into the method. Isn't the existence of lambda expressions just to replace anonymous internal classes? And if this interface defines a Java-type interface, you can use lambda expressions. why is that? The final guess is that kotlin wraps another layer in the middle when calling each other with java, and we directly use kotlin to define that this interface does not have the middle layer. The set method we define is not a higher-order function, so of course we cannot use lambda expressions.

Next, use the idea of ​​kotlin to implement callbacks

Use higher-order functions to implement

One important difference between kotlin and java is functional programming. In the idea of ​​functional programming, functions are first-class citizens. When using kotlin, we should use this thinking more to think about problems. Kotlin provides high-order functions, which can directly use a function as the return value. It is difficult for me who are accustomed to Java programming at the beginning. Below I will write down my idea of ​​implementing a high-order function step by step, hoping it will be helpful to everyone.

First of all, the ones that can be thought of is function delivery. You need to use lambda to replace anonymous internal classes, which can be implemented in this way.

//From the most basic, implement anonymous internal classes through lambda(object :  {
    override fun onLabelCheck(label: String) {
     println(label)
    }
})
// First of all, there is only one method onLabelCheck(label: String)// Therefore, you can write the lambda expression as followsvar lam: (String) -> Unit = { label -> println(label) }

Then, you need to pass the written lambda in. At this time, you need to require the setOnLabelCheckedListener method to be a higher-order function.

  // Here we receive an expression lam we modified above. Its internal implementation should be to assign e to an object of the current class  fun setOnLabelCheckedListener(e: (String) -> Unit) {
     = e
  }
 
  //Obviously this should be the lisenter  var linsnter: (String) -> Unit = {}

Finally, use linsnter to make the callback

  private fun initView(context: Context) {
     { radioGroup, i ->
      linsnter(<RadioButton>(i).())
    }
  }

Final code result:

class MyView{
  var linsnter: (String) -&gt; Unit = {}

 private fun initView(context: Context) {
     { radioGroup, i -&gt;
      linsnter(&lt;RadioButton&gt;(i).())
    }
 }

 fun setOnLabelCheckedListener(e: (String) -&gt; Unit) { 
   = e
 }
}
  // Omit the variable lam when calling and use an expression directly   { label -&gt;
    println(label)
  }

The final code has two biggest differences from the previous code. One is that there is no interface definition, and the other is that there is no anonymous internal class.

Better use of higher-order functions

The use of higher-order functions can make our code more concise, such as the following code:

  fun refreshData(e: ((Boolean, String) -&gt; Unit)): Boolean {

    if (!().isLogin) {
      e(false, "Not logged in")
      return false
    }

    (ApiParamter(), object : ApiListener&lt;ResponseData&gt; {
      override fun onApiCompleted(data: ResponseData?) {
          e(true, "success")
      }

      override fun onApiError(errorCode: Int, errorCodeMessage: String) {
         e(false, errorCodeMessage)
      }
    })
    return true
  }

Then when calling it, it can be done like this:

    { isSuccess, msg ->
      //do something
  }

Isn't it very simple? It saves writing another interface. At the same time, it is also OK if you use java to call the refreshData method:

    (new Function2<Boolean, String, Unit>() {
      @Override
      public Unit invoke(Boolean aBoolean, String s) {
        // do something
        return null;
      }
    });

Kotlin provides a series of Function interface classes for Java to use when calling higher-order functions. It supports up to 22 parameters if you are interested, you can check it out.

The above is how to use higher-order functions in Kotlin to replace traditional callback functions. Please correct any wrong things. I hope I can give you a reference and I hope you can support me more.