Higher-order function in Kotlin
Level 4190 keystrokes
operate takes a function of type (Int, Int) -> Int as its last parameter and applies it to a and b. Because it is the last parameter, the lambda can be written after the parentheses (trailing lambda).
Kotlin code
// op has a function type: it takes two Ints and returns an Int1fun operate(a: Int, b: Int, op: (Int, Int) -> Int): Int { // Call the passed function with a and b and return its result2 return op(a, b)3}4 // Trailing lambda after the parentheses: 5 + 3 = 85val sum = operate(5, 3) { x, y -> x + y }// Same function, different behavior: 5 * 3 = 156val product = operate(5, 3) { x, y -> x * y }// Print 8, 157println("$sum, $product")Output
8, 15
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Kotlin code and how often they appear.
,× 9(× 6)× 6:× 4-× 3{× 3}× 3>× 3"× 2=× 2