How to create an anonymous implementation of an interface?
There are examples in the documentation for anonymous classes, but not for interfaces.
This is how I created an instance of an interface:
fun TileSet.union(another: TileSet) : TileSet =
object : TileSet {
override fun contains(x: Int, y: Int) : Boolean =
[email protected](x, y) || another.contains(x, y)
}
Notice that, unlike in the example from documentation, there are no parentheses after object : TileSet
.
I was experimenting a little bit, and I was surprised to find that you can implement Java functional interfaces using Kotlin lambdas:
// Implementing Java functional interfaces using lambdas
val greeter = Consumer<String> { println("Hi $it") }
val dice = Supplier { ThreadLocalRandom.current().nextInt(1, 7) }
But when you implement Kotlin functional interfaces, you need the full ceremony:
// Implementing a Kotlin functional inteface with lambdas is not possible
val greeter = object : MyConsumer<String> {
override fun accept(x: String) {
println("Hi $x")
}
}
@FunctionalInterface
interface MyConsumer<T> {
fun accept(x:T)
}
I wonder why the full anonymous class syntax is needed when implementing Kotlin intefaces from the very Kotlin!
Maybe they want you to use functions instead? That could be done like this.
// If you want to use lambdas, define a function instead of an interface
val greeter: MyConsumerFunction<String> = { println("Hi $it") }
typealias MyConsumerFunction<T> = (T) -> Unit
Anyway, if anyone knows anything about this, please let me know! :)