2

In the below code, what is wrong with the second add?

val lambdas  = mutableListOf<()->Unit>()
lambdas.add{println("a")} // this compiles fine
lambdas.add{()->println("b")} //why can't I do this?


error: expecting a name
lambdas.add{{()->println("b")}}
1
  • Read this to learn the syntax of lambda's in kotlin. Commented Feb 29, 2020 at 13:27

1 Answer 1

3

You can't declare a lambda the way you are trying to

val right: () -> Int = { 1 } // Convenient way to declare a lambda without parameters
val alsoRight: () -> Int = { -> 1 } // The right way to explicitly declare a lambda without parameters
val wrong: () -> Int = { () -> 1 } // The wrong way to declare a lambda without parameters

That line should look like this:

lambdas.add { -> println("b") }
Sign up to request clarification or add additional context in comments.

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.