The fact that you can extend a functional type in kotlin (jvm) is an accidental result of the way function types work on the jvm (as Varia) explained. That said I don’t think I have ever seen any code doing this in kotlin and I can’t think of a good reason to use it over normal lambdas.
Compare
class MyCalback : (Data) -> Unit {
override operator fun invoke (data: Data) {
TODO()
}
}
to
val myCallback = { data: Data ->
TODO()
}
Using the lambda syntax is much cleaner. I guess there are might be some special situation where this is not sufficent but I have never seen or heard about it. I guess you could group multiple callbacks into one class
class MySpecialCallback: SpecialCallback, () -> Unit {
override fun onError() = TODO()
override fun onSuccess() = TOOD()
override operator fun invoke() = onSuccess()
}
but in that case it’s not really necessary to implement a functional interface and might even lead to hard to find bugs (is invoke
the onSuccess
or onError
case).
Also you can’t extend multiple functional interfaces that just differ in their parameter/return types. They have to differ in the number of arguments.
class Foo: (Int) -> Unit, (String) -> Unit {
override fun invoke(i: Int) = println(i)
override fun invoke(s: String) = println(s)
}
generates this compiler error
Type parameter P1 of ‘Function1’ has inconsistent values: Int, String
A supertype appears twice