When you want to create an object using a lambda expression while defining a new type that works like a function.
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.
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