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 Int
1fun operate(a: Int, b: Int, op: (Int, Int) -> Int): Int {
// Call the passed function with a and b and return its result
2 return op(a, b)
3}
4
// Trailing lambda after the parentheses: 5 + 3 = 8
5val sum = operate(5, 3) { x, y -> x + y }
// Same function, different behavior: 5 * 3 = 15
6val product = operate(5, 3) { x, y -> x * y }
// Print 8, 15
7println("$sum, $product")

Output

8, 15
Practice typing this code

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

More Kotlin examples at level 4

← Kotlin typing practice