Mobile Development
Kotlin
Subjective
Oct 04, 2025
What are higher-order functions and lambdas in Kotlin?
Detailed Explanation
Higher-order functions and lambdas enable functional programming in Kotlin:\n\n1. Higher-order Functions\n• Functions that take functions as parameters\n• Functions that return other functions\n• Enable powerful abstractions and reusable code\n\n2. Lambda Expressions\n• Anonymous functions with concise syntax\n• Can be passed as arguments\n• Example:\n\nval sum = { a: Int, b: Int -> a + b }\nval square: (Int) -> Int = { it * it }\n\n\n3. Function Types\n\n// Function type declarations\nval operation: (Int, Int) -> Int = { a, b -> a + b }\nval predicate: (String) -> Boolean = { it.isNotEmpty() }\n\n\n4. Higher-order Function Examples\n\nfun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {\n return operation(x, y)\n}\n\n// Usage\nval result = calculate(5, 3) { a, b -> a * b } // 15\n\n\n5. Collection Operations\n\nval numbers = listOf(1, 2, 3, 4, 5)\n\nval doubled = numbers.map { it * 2 }\nval evens = numbers.filter { it % 2 == 0 }\nval sum = numbers.reduce { acc, n -> acc + n }\n\n// Chaining operations\nval result = numbers\n .filter { it > 2 }\n .map { it * it }\n .sum()\n\n\n6. Trailing Lambda Syntax\n\n// When lambda is last parameter\nrepeat(3) {\n println("Hello")\n}\n\n// Instead of\nrepeat(3, { println("Hello") })\n\n\n7. Benefits\n• Code reusability and modularity\n• Functional programming patterns\n• Cleaner API design\n• Better abstraction capabilities
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts