Max's Blog

Max's Blog

Kotlin convenience function to pass an interface object

Subscribe to my newsletter and never miss my upcoming articles

Some time ago I saw a quick & neat convenience function in the library Coil. I haven't seen it in other projects yet and that's why I want to mention it here once, since I keep using it in my projects.

Instead of creating an object of an interface and implementing all member functions of it, we are just going to call the member functions we need - in a much sleeker way.

Let's say I have an interface called Listener:

interface Listener {
    fun onStart(id: String)
    fun onEdit(id: String)
    fun onDelete(id: String)
}

The convenience function for the interface:

   inline fun listener(
            crossinline onStart: (id: String) -> Unit = { _ -> }
            crossinline onEdit: (id: String) -> Unit = { _ -> }
            crossinline onDelete: (id: String) -> Unit = { _ -> }
    ) = listener(object : Listener {
        override fun onStart(id: String) = onStart()
        override fun onEdit(id: String) = onEdit(id)
        override fun onDelete(id: String) = onDelete(id)
    })

Now, you can simply call the function listener(...) and pick the parameters for which you need to override the corresponding interface functions.

listener(onStart = ::start, onEnd = ::end)

fun start(id: String) {
   // Do something
}

fun end(id: String) {
   // Do something
}

Quite convenient, right?

#kotlin#kotlin-beginner#android#android-apps
 
Share this