Functional interfaces are great - being able to declare
fun interface AnInterface {
fun aFunction()
}
// sometime later
AnInterface {
}
really clarifies the code. The ability to just declare the instance of an interface is very concise.
Why when we have more than one function to we need the syntax
object: AnotheInterface {
}
instead of
AnotheInterface {
}
It is just a small point, but it seems anomalous. I know the context within the braces is different, but I don’t think that would create confusion.
So if you have multiple functions, that syntactic sugar no longer works. I would assume that trying to use the same syntax as syntactic sugar for defining one function vs a block where you override multiple functions would introduce a lot of complexity into the compiler.
fun interface MyFunctionalInterface {
fun myFunction(first: String, second: String): String
}
interface MyInterface {
fun myFunction(first: String, second: String): String
fun myOtherFunction(first: Int, second: Int): Int
}
val functional = MyFunctionalInterface { first, second ->
first + second
}
val nonFunctional = MyInterface {
override fun myFunction(first: String, second: String): String {
return first + second
}
override fun myOtherFunction(first: Int, second: Int): Int {
return first + second
}
}
Although to us, the difference looks reasonably obvious, I can easily imagine it being quite complicated for the compiler.
@Skater901 Yes you have captured exactly what I meant with a clear description, so many thanks for that.
As to whether the compiler knows the difference, I am not an expert but it seems that the compiler knows enough to complain when you try the shortened form for a non-functional interface.
Are there any other benefits of this than saving 8 chars? For functional interfaces we skip the function definition as well, so in the case of simple implementations like it * 2, actually 95% of the code is a bloat code that can be skipped. In the case of regular interfaces we can’t do that easily, so it is the other way around - by removing object : we save maybe 5% of the code .
Goal of Kotlin is not to be as shortest as possible, but to be the most concise. object : says explicitly we create an instance. Fun interface is a little different. It is something between an interface and a function type. If we create it with the mentioned syntax, we think of it as a function/lambda, but of a specific type. In some cases we can even skip its type name entirely. Such approach doesn’t make sense for non-functional interfaces where we always think in the terms of classes/objects/interfaces.