Marti Serra Molina
Marti Serra Molina

Reputation: 473

I want to call an object method from a function that has been passed as an argument to the object constructor

I have this block of code where I want to call a method of NavDrawerItemAdapter from the function of ItemSelectedListener.

Is there a way that I can do that?

private fun setupNavDrawer() {
        binding.aMainNavDrawerI.iNavDrawerListNavDrawerItemsRv.apply {
            setHasFixedSize(true)
            adapter = NavDrawerItemAdapter(NavDrawerItemAdapter.ItemSelectedListener {
                
            })
        }
    }

Upvotes: 0

Views: 32

Answers (1)

Eddie Lopez
Eddie Lopez

Reputation: 1139

That pretty much depends on whether the ItemSelectedListener lambda receives the adapter as argument (can't tell from your code).

For example, if this(or similar) where the definition of the listener class:

class ItemSelectedListener(function: (NavDrawerItemAdapter) -> Unit) {

}

You could call:

val adapter = NavDrawerItemAdapter(NavDrawerItemAdapter.ItemSelectedListener {
    it // is an adapter!
})

That is because you're trying to reference something that has not been created yet.

Another option would be to use a setter for the listener if it were available.

Upvotes: 1

Related Questions