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
)
In your first example, just remove return@setListener
myObject.setListener{p1, p2 -> false}
In your second example, you have to be careful:
setListener{{
must be setListener{
. 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
}
}
If I understand correctly, you have something like this:
fun setListener(f: (Int, Int) -> Boolean) {
f(1, 2)
}
setListener { p1, p2 -> true }
Of course you can extract the logic into another function like this:
fun logic (i: Int, i2: Int) :Boolean {
//complex stuff
return true
}
setListener(::logic)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With