Nachahmung der funktionalen Schnittstelle von Java mit Kotlin

Wenn Sie ein Objekt mit einem Lambda-Ausdruck erstellen möchten, während Sie einen neuen Typ definieren, der wie eine Funktion funktioniert.

Hintergrund

In Java kann ein Schnittstellenobjekt (= funktionale Schnittstelle) mit nur einer abstrakten Methode durch einen Lambda-Ausdruck erstellt werden.

@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 bietet auch Lambda-Ausdrücke und anonyme Funktionen, mit denen Sie funktionale Objekte erstellen können. Dies dient jedoch nur zum Erstellen eines Funktionsobjekts, und es ist nicht möglich, eine Funktion zu erstellen, z. B. ein Schnittstellenobjekt, das einen Funktionstyp erbt. Daher führt der folgende Code zu einem Kompilierungsfehler.

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))
}

stattdessen

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

Es ist mühsam, es einzeln zu schreiben.

Methode

Definiert eine Funktion, die eine Funktion übernimmt und eine Schnittstelle zurückgibt. Die eigentliche Verarbeitung wird an die empfangene Funktion delegiert.

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

Nachahmung der funktionalen Schnittstelle von Java mit Kotlin
Einführung der Funktionsschnittstelle
[Java] Funktionsschnittstelle
Informationen zur Java-Funktionsschnittstelle
Grundlegende funktionale Schnittstelle, die in 3 Minuten verstanden werden kann
Aufrufbare Schnittstelle in Java
Java-Standardfunktionstyp-Schnittstelle
Ein Überprüfungshinweis zur Funktionsoberfläche
Große Dezimalstelle in Kotlin
Probieren Sie den Funktionstyp in Java aus! ①
Implementieren Sie eine funktionsähnliche schnelle Sortierung in Java
Apache POI Excel mit Kotlin
Implementierung von HashMap mit Kotlin