Issue
Which one of the following is the preferred way to create a listener/callback in Kotlin Android? I can't seem to find any info online
var onClickListener: (View) -> Unit
.....
view.onClickListener = {
println("Clicked!")
}
or
private var onClickListener: (View) -> Unit
fun setOnClickListener(listener: (View) -> Unit) {
this.onClickListener = listener
}
.....
view.setOnClickListener {
println("Clicked!")
}
Is there any difference? The second one looks "cleaner" and it's what all those listeners in Java Android are converted to
Solution
Use the first one in Kotlin; when calling from Java, it will be setOnClickListener
either way.
The second one doesn't let you get the onClickListener
value from outside the class, so it can be used if you really want to prevent such access for some reason.
and it's what all those listeners in Java Android are converted to
This is simply what you get when converting a private field with a setter method and no getter. There is no special treatment for callbacks or for Android (as far as I know).
But the reason such callbacks don't usually have a getter in Java is because you need more code to write it and it's rarely useful; in Kotlin you need more code to omit it.
Answered By - Alexey Romanov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.