TooLazy :
im a bit confused about kotlin lambda expression. Can not find a proper answer.
In Java i can set a listener with tho parameters like that:
myObject.setListener(new MyListener() {
@Override
public boolean doSmth(int pos, int value) {
switch(..) {
....
}
}
})
With lambda:
myObject.setListener((p1, p2) -> {
switch(..) {
....
}
})
In Kotlin i can do smth like that:
myObject.setListener{p1, p2 -> return@setListener false}
or
myObject.setListener{{p1, p2 ->
if (p1) {
return@setListener true
} else {
return@setListener false
}
}}
But its really ugly. Is there any way to do it easier? Of i can use smth like that:
myObject.setListener{p1, p2 -> myFunc(p1, p2)}
But what if i wanna put my logic into that listener (it could be complex, not just if else return
)
guenhter :
In your first example, just remove return@setListener
myObject.setListener{p1, p2 -> false}
In your second example, you have to be careful:
- You have one pair of curly brackets too much
setListener{{
must besetListener{
. Else you would create a lambda within a lambda. You again just remove the
return
. This is an expression body where the resulting parameter is just used.myObject.setListener{p1, p2 -> if (p1) { true } else { false } }
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=473304&siteId=1