Considering a move to Kotlin? Coming from a Java background? In this short series of blog posts, I’ll take a look at familiar, straightforward Java concepts and demonstrate how you can approach them in Kotlin. While many of these points have already been discussed in earlier posts by colleagues, my focus is simple: how you used to do it in Java, and how you do it in Kotlin.

Case 6: Passing functions around sounds scary.

Until you try it.

Remember, a higher-order function just is a function that takes another function as a parameter or returns one.

The problem

We want behavior as a parameter. Simple math. Different operations.

The Java way

// Higher-order function with a lambda
private int calculate(int a, int b, Operation operation) {
  return operation.apply(a, b);
}
@FunctionalInterface
interface Operation {
  int apply(int a, int b);
}

Usage:

int r = calculate(5, 3, (a, b) -> a * b);

This works, but requires:

  • a functional interface

  • extra ceremony

The Kotlin way

// Higher-order function with a lambda
fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
  return operation(a, b)
}

Usage:

val r = calculate(5, 3) { a, b -> a * b }

Functions are first-class citizens. No interfaces required.

Why this matters

Less ceremony lowers the barrier. Lower barriers lead to better abstractions.

Takeaway

Java allows functional programming. Kotlin encourages it.

shadow-left