Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin lambda with several parameters

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)

like image 873
TooLazy Avatar asked Nov 02 '17 11:11

TooLazy


2 Answers

In your first example, just remove return@setListener

myObject.setListener{p1, p2 -> false}

In your second example, you have to be careful:

  1. You have one pair of curly brackets too much setListener{{ must be setListener{. Else you would create a lambda within a lambda.
  2. 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
        }
    }
    
like image 150
guenhter Avatar answered Oct 06 '22 00:10

guenhter


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)
like image 43
s1m0nw1 Avatar answered Oct 06 '22 00:10

s1m0nw1