I came across something and wondered all the time why you should do this.
You implement an interface in Kotlin through a simple function type:
class Divider : (Int, Int) -> Double {
override fun invoke(numerator: Int, denominator: Int): Double = ...
}
But why should I do this? Why should I add an interface in that way? I think its only possible to add one function and not more. Or is it an advantage that I can implement a function with a function body and not only the function head like in normal interfaces? I think it is possible in Java to add default methods to interfaces with a function body. So maybe it is something like that?
It is probably not very useful to write a class that only implements a function type interface; however, it might be useful to write a class that can among other things be used in place of a function.
An example from the standard library is the
KProperty1interface. You can write code like this:Here,
C::idis a property reference of typeKProperty1<C, Int>, and it can be used as an argument toList.mapin place of a lambda becauseKProperty1<C, Int>extends(C) -> Int. However,KProperty1has a lot of other uses besides being passed as a function.