I have a pretty common friction point I wanted to discuss.
Often I have interfaces with default implementations that I want to make final. So they’re better as extension methods, except for one problem - imports and auto complete.
Take the following example:
interface Positionable {
val position: Vector3
val x: Float
get() = position.x
val y: Float
get() = position.y
}
I don’t want x or y to be open; they should always be derived from the position value, but changing this to:
val Positionable.x: Float
get() = position.x
Requires an import and makes auto-complete more difficult.
My suggestion is to either: allow interfaces to set a method with a default implementation as final
or
extension methods defined in the same file as the interface don’t require a separate import.
allow interfaces to set a method with a default implementation as final
That is not possible. Kotlin interfaces are also Java interfaces, and there is no such thing in Java as final interface method.
extension methods defined in the same file as the interface don’t require a separate import.
That would introduce namespace pollution. Imagine you have a file with 20 interfaces and some global methods. Now you import one interface, and suddenly everything is imported.
It is, kind of. You could think of it as an alternate syntax for an extension method on an interface. In the bytecode every final method would be implemented as an extension function. The only difference is that it would be automatically imported with the interface.
That all said, I am a big supporter of star imports in any case so I don’t really care either way. But I guess that is a different discussion.
In the bytecode every final method would be implemented as an extension function.
Right.
That all said, I am a big supporter of star imports in any case so I don’t really care either way. But I guess that is a different discussion.
I don’t like manually touching imports, I like letting the IDE take care of that
That would introduce namespace pollution. Imagine you have a file with 20 interfaces and some global methods. Now you import one interface, and suddenly everything is imported.
I’m just talking about the extension methods in the same file as the class/interface imported, not everything in that file.