Search code examples
kotlinanko

How can I adapt my Kotlin Higher-Order function to take a parameter?


In Kotlin I have the following:

fun ViewManager.controlButton(body: () -> Unit) = frameLayout {
...
}

private fun captureAndInsert() {
    println("captureAndInsert is called!")
}

Inside an Anko view:

controlButton(this@MemoryFragmentUi::captureAndInsert)

This works fine.

Now I need to pass a parameter to captureAndInsert so it will look like this:

private fun captureAndInsert(myInt: Int) {
    println("captureAndInsert is called!")
}

How can I adapt ViewManager.controlButton and the call inside the Anko view to accept the parameter?

EDIT:

Ok, so I can do this:

fun ViewManager.controlButton(body: (myInt: Int) -> Unit) = frameLayout {
...
}

But how do I call that from the Anko view?


Solution

  • To accept an (Int) -> Unit function, you simply need to add the Int parameter to the function type in controlButton parameter:

    fun ViewManager.controlButton(body: (Int) -> Unit) = frameLayout {
        ...
    }
    

    The call of body happens inside controlButton, so you also need to pass the argument for the lambda to the parameter list of controlButton:

    fun ViewManager.controlButton(body: (Int) -> Unit, v: Int) = frameLayout {
        body(v)
    }
    
    //call
    controlButton(this@MemoryFragmentUi::captureAndInsert, 5)