11

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)

1
  • You said it is ugly, but compared to what ? Your java version is empty so off course it is cleaner... Can you specified the problem. Commented Nov 2, 2017 at 12:02

2 Answers 2

21

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
        }
    }
    
Sign up to request clarification or add additional context in comments.

Comments

10

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.