anber
anber

Reputation: 3665

Functional type with let - unresolved reference: invoke

I have onClick functional type declared as class field val onClick: (() -> Unit)? = null

And want to use it like this:

if (onClick != null) {
    item.setOnClickListener { onClick.invoke() }
}

This code works, but when I replaced it with let function, it shows error unresolved reference: invoke:

onClick?.let {
    item.setOnClickListener { it.invoke() }
}

Why it happens?

Upvotes: 1

Views: 302

Answers (1)

Yoni Gibbs
Yoni Gibbs

Reputation: 7036

The it here is the receiver of the second lambda (being passed into setOnClickListener), not the first lambda (let). Declare the parameter to the first lambda by giving it a name explicitly, then use that, e.g.

onClick?.let { handler ->
    item.setOnClickListener { handler.invoke() }
}

Upvotes: 2

Related Questions