问题
I have few click listeners in my code like below:
tvLogin.setOnClickListener {
hideKeyBoard(it)
login()
}
tvForgotPassword.setOnClickListener {
hideKeyBoard(it)
navigateToForgetPassword()
}
I want to modify the passed block of code to always invoke hideKeyBoard(view)
and then my function.
Is there a way to create a higher order function that would modify a block of code and invoke passed function?
I have tried something like below:
val clickListener: (View,()->Unit) -> Unit
But not sure how it would work.
Can anyone please help how to achieve?
回答1:
I'm not sure I understand fully what you mean, but maybe something like this:
fun addCallTo(lambda: (View) -> Unit): (View) -> Unit {
return {
hideKeyboard(it)
lambda(it)
}
}
// usage:
tvLogin.setOnClickListener(addCallTo { view -> login() })
回答2:
You can extend View.OnClickListener
and pass lambda to it:
inner class HideKeyboardClickListener(private val lambda: () -> Unit) : View.OnClickListener {
override fun onClick(v: View) {
hideKeyboard(v)
lambda()
}
}
And then set it like this:
tvForgotPassword.setOnClickListener(HideKeyboardClickListener {
navigateToForgetPassword()
})
来源:https://stackoverflow.com/questions/50693148/modifying-an-anonymous-function-to-invoke-another-anonymous-function-in-kotlin