Vector
Vector

Reputation: 3235

kotlin call function with android view

We are trying to understand calling a function in Kotlin

The function looks like this

    fun onSIMPLE(view: View){
    val snack = Snackbar.make(view,"This is a simple Snackbar", Snackbar.LENGTH_LONG)
    snack.show()
}

And the call is made this way

btnSB2.setOnClickListener {onSIMPLE(it)}

What we do not understand is how does one know to use the keyword "it"?
Who ever created the keyword "it" must have never searched the Web

We plugged every reasonable keyword in the ( ) to solve the issue
YES we also looked at the documentation
Is there a better way to construct the function or make the call?

Upvotes: 0

Views: 1080

Answers (2)

Ervin Szilagyi
Ervin Szilagyi

Reputation: 16775

setOnClickListener expects a lambda as a parameter, using a Java-like approach, this should look like this:

btnSB2.setOnClickListener({
    v:View -> onSIMPLE(it)
})

Also, if the lambda is the last parameter for a given function, it can be specified outside of the parenthesis, which would look like this:

btnSB2.setOnClickListener {
    v:View -> onSIMPLE(it)
}

It is common for lambda functions to have a single parameter. For these functions, Kotlin maintains the it keyword. Knowing this, the code becomes:

btnSB2.setOnClickListener {
    onSIMPLE(it)
}

Upvotes: 1

veritas1
veritas1

Reputation: 9170

it is the implicit name for a single parameter lambda. You can override as you wish, e.g:

btnSB2.setOnClickListener { view -> onSIMPLE(view)}

Upvotes: 2

Related Questions