Kotlin how to create callback

Callback function

I am SDK developer of mobile. We will provide API for developers.

For Java, we will create Listener class(interface) to delegate process after doing something

Kotlin

For Kotlin, the answer is simple. We can create a method type argument

This is a sample.

API Class

object CallbackExample {

    fun getCount(success: (count: Int) -> Unit, failed: (e: Error) -> Unit) {
        // Do something
        try {
            val a = 3
            success(a)
        } catch (e: Error) {
            failed(e)
        }
    }
}

Object is singleton class. I implemented simple method with success callback and failed callback, actual one is more complicated, but this example is simple.

success and failed are called into contents of method

Callback have argument, and it means callback delegate can use this parameter, of course we don’t need to have argument, in this case, use ().

Return “Unit” type

How to use?

This is usage.

fun main() {
    CallbackExample.getCount( { count ->
        println(count) // success
    }, { e ->
        println(e.message) // failed
    })
}

It’s simple. Added 2 methods into argument and handle.

Android
スポンサーリンク
Professional Programmer2

コメント