Junior — Middle
Can you explain what an anonymous function is in programming and how it is used?
sobes.tech AI
Answer from AI
An anonymous function is a function without a name, which is usually created and used "on the spot", without the need to declare it separately. In Android (Java or Kotlin), anonymous functions are often used for event handling, callbacks, or in functional programming.
Example in Kotlin:
val sum = { a: Int, b: Int -> a + b }
println(sum(3, 4)) // Outputs 7
Here, { a: Int, b: Int -> a + b } is an anonymous function that adds two numbers. Such functions are convenient to pass as parameters to other functions or to use for concise data processing.