Home > Enterprise >  Why can't I pass this method directly into the constructor, why do I need to use a lambda?
Why can't I pass this method directly into the constructor, why do I need to use a lambda?

Time:07-26

I just started to learn Kotlin yesterday, so brace yourself for a potentially stupid question.

class MyCustomViewAdapter(private val callback: (position: Int) -> Unit) : RecyclerView.Adapter<MyCustomViewHolder>() {
    ...
}

When I try to initialize this class, I need to pass in a callback parameter to receive events.

MyCustomViewAdapter({ position -> onClickFlowerCallback(position)}) // this works

MyCustomViewAdapter(onClickFlowerCallback) // this doesn't work?

private fun onClickFlowerCallback(position: Int) {
    println("We have successfully received click from position #"   position.toString())
}

Can someone enlighten me to why this is happening?

CodePudding user response:

What you want to do is pass a method reference — you just need the right syntax, which is ::onClickFlowerCallback.

Similarly, to call someObject.onClickFlowerCallback, you'd pass someObject::onClickFlowerCallback.

You can also pass a reference to a top-level function, local function, extension function, constructor, member property, top-level property, or extension property using the same syntax. See the docs for more.

  • Related