SoFunction
Updated on 2025-04-07

Kotlin implements simplified calls to multifunction interfaces

For an interface that declares multiple methods, we sometimes focus on a few key methods when using them, and do not need to implement all of them. However, due to the syntax limitation of interface calls, we have to display the declaration in the code to implement methods that we do not care about. There are also ways to simplify interface calls in Java, such as the PageChangeListener interface when the ViewPager listens to page switching in Android. The official provides a simple class: to simplify calls.

For Kotlin, it can be used similarly to using Java to implement simplified calls to multifunction interfaces, except that the object keyword is used and there will still be more code. Here, since Kotlin's syntax is more flexible, implementing this call should have its own unique way, making it less code and more intense.

Let’s take a small example, let’s briefly introduce simplified calls to implement multifunction interfaces similar to Java. First, show what simplified interface calls are, and second, make comparisons. All the examples here are written in kotlin.

1. Declare the interface CallBack and call the class Worker

 interface CallBack {
  fun onSuccess(str: String)
  fun onFailure(code: Int)
}
class Worker {
  var callback: CallBack? = null
  fun done(str: String) {
    callback?.onSuccess(str)
  }

  fun fail(code: Int) {
    callback?.onFailure(code)
  }

  fun setCallBack(lis: CallBack) {
    callback = lis;
  }
}

2. Directly call the interface and use the object keyword. At this time, it is assumed that you do not care about the success method, but the declaration must be displayed.

 Worker().apply {
     setCallBack(object : CallBack {
      override fun onSuccess(str: String) {
      }
      override fun onFailure(code: Int) {
        toast("$code")
      }
    })
  }.fail(110)
//Result: Toast: 110

Style simplified calls, declare simplified class SimCallBack

public class SimCallBack implements CallBack{
  @Override
  public void onSuccess(@NotNull String str) {
  }
  @Override
  public void onFailure(int code) {
  }
}

Style simplified display of calls, no need to display the statement if you don't care about onSuccess

 Worker().apply {
    setCallBack(object : SimCallBack() {
     override fun onFailure(code: Int) {
        (code)
        toast("$code")
     }
    })
}.fail(110)

The above calls with a strong Java flavor not only have a mixed code style, but also have a redundant code. The point is here, how can Kotlin overcome the above two points? See examples.

1. It is still CallBack interface, but its simplified class needs to be done in Kotlin style:

 class SimpleCallBack : CallBack{
  private var _OnSucess: ((str: String) -> Unit)? = null
  fun success(listener: (str: String) -> Unit) {
    _OnSucess = listener
  }
  override fun onSuccess(str: String) {
    _OnSucess?.invoke(str)
  }
  private var _OnFailure: ((code: Int) -> Unit)? = null
  override fun onFailure(code: Int) {
    _OnFailure?.invoke(code)
  }
  fun fail(listener: (code: Int) -> Unit) {
    _OnFailure = listener
  }
}

Two function type variables _OnSucess and _OnFailure are declared, which is to internally decompose the original large interface CallBack. Then the corresponding methods success and fail are declared, with the purpose of assigning values ​​to the variable small interface. Next is the processing of the original interface method, such as the operation of the original interface method onSuccess(str: String) _OnSucess?.invoke(str), the purpose is to realize the transfer of the interface callback result. The purpose of doing these is to prepare for future simplified calls.

2. The call to the Worker class also needs to be processed. The code is basically the same as the original ones, but the following methods are added.Notice,If it is not for compatible with Java methods, the original setCallBack can no longer be declared and directly assign values. Therefore, the new method can be regarded as a replacement for the original setCallBack method.

 fun setCallBacker(listener: SimpleCallBack.() -> Unit) {
    var ca = SimpleCallBack()
    ()
    setCallBack(ca)
 }

Note the name. This method accepts a function parameter. The function of the method is to internally generate a simplified interface object SimpleCallBack, and then register the calling class to the interface. Then execute the function parameters passed in. Why do you need this? It is to use the flexible closure {} in the kotlin syntax. In addition, with powerful function extension syntax, it is relatively easy to add this method without changing the original class.

3. Finally, let’s take a look at the call method:

 Worker().apply {
    setCallBacker {
      success { toast(it) }
      fail { }//If not required, no declaration can be displayed    }
 }.done("Finish")
//Result: Toast: Completed

The final result shows that when calling the multifunction interface CallBack, there is no need to declare the interface again, but directly declare the method you want to use in the closure, and then execute the operation in the corresponding method closure. The style is completely kotlin and is very easy to use.

The sharing ends, I hope it will be helpful to readers.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.