Imitate Java's functional interface in Kotlin

When you want to create an object using a lambda expression while defining a new type that works like a function.

background

In Java, an interface object (= functional interface) that has only one abstract method can be created by a lambda expression.

@FunctionalInterface
interface Composable {
    int apply(int v);

    default Composable compose(Composable other) {
        return v -> { return this.apply(other.apply(v)); };
    }
}

class Main {
    public static void main(String[] args) {
        Composable f = v -> { return v + 2; };
        Composable g = v -> { return v * 2; };
        System.out.println(f.compose(g).apply(2));
    }
}

Kotlin also provides lambda expressions and anonymous functions that you can use to create functional objects. However, this is just for creating a function object, and you cannot create something like a function, for example, an interface object that inherits a function type. Therefore, the following code will result in a compilation error.

interface Composable {
    fun apply(v: Int): Int

    fun compose(other: Composable): Composable = { this.apply(other.apply(it)) }
}

fun main(args: Array<String>) {
    val f: Composable = { it + 2 }
    val g: Composable = { it * 2 }
    println(f.compose(g).apply(2))
}

instead of

object : Composable {
    override fun apply(v: Int): Int { ... }
}

It is troublesome to write it one by one.

Method

Defines a function that takes a function and returns an interface. The actual processing is delegated to the received function.

interface Composable {
    fun apply(v: Int): Int

    fun compose(other: Composable): Composable = composable { this.apply(other.apply(it)) }
}

fun composable(f: (Int) -> Int) = object : Composable {
    override fun apply(v: Int): Int = f(v)
}

fun main(args: Array<String>) {
    val f = composable { it + 2 }
    val g = composable { it * 2 }
    println(f.compose(g).apply(2))
}

Recommended Posts

Imitate Java's functional interface in Kotlin
Functional interface introduction
[Java] Functional interface
About Java functional interface
Basic functional interface that can be understood in 3 minutes
Callable Interface in Java
java standard functional interface
Functional interface review notes
Big Decimal in Kotlin
Try functional type in Java! ①
Implement functional quicksort in Java
Apache POI Excel in Kotlin
Implementation of HashMap in kotlin