Fone
Fone

Reputation: 21

How to determine which method its overriding in Kotlin?

In the following code, I'm confused as to how do you know its onClick method of OnClickListener its overriding ?

fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()


        }

Upvotes: 0

Views: 139

Answers (2)

Richard Dapice
Richard Dapice

Reputation: 885

One thing to note is that lambda expression like this is only possible when the lambda takes one function. To see what this is just to pay attention when creating your lambda.

We see here that when we create the onClick its expected parameter is View.OnClickListener. So an OnClick with a receiver of View. Decalring onClickListener So we can give it that. OnClickListener As we can see it was expecting one interface wich has one function, OnClickListener. SAM-Redundant We can simplify this due to the fact that we are only expecting one interface function on our receiver "view" so it is implicit. Simplified on click.

As stated before, we can only have a lambda like this with a single function, so if we look into our onClickListener we can see a single interface which has a single method so the lambda is implicit:

onClick

Upvotes: 1

sanoJ
sanoJ

Reputation: 3128

OnClickListener only have the onClick method. Therefore Kotlin will use a lambda expression to simplify it. The normal code to the OnClickListener is as given below.

setOnClickListener(object : View.OnClickListener {
    override fun onClick(v: View?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
})

But if you have more than one method, this won't be the case. For example setOnQueryTextListener on a SearchView you need to override the two functions separetely.

setOnQueryTextListener(object : SearchView.OnQueryTextListener {
    override fun onQueryTextSubmit(query: String?): Boolean {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onQueryTextChange(newText: String?): Boolean {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
})

You can find more about Lambda functions from this doc

Upvotes: 1

Related Questions