Jire
Jire

Reputation: 10310

Java doesn't allow final default methods.. but does Kotlin?

If you attempt to create an inline function on an interface, you will face an error: 'inline' modifier is not allowed on virtual members. Only private or final members can be inlined

the error pictured in IDEA

I understand that this is because the function is virtual because it can be overridden.

If we were able to declare "closed" functions, these functions would not be virtual, and therefore able to be inlined which is very useful!

Using "private" gives us a non-virtual, "closed" function, but then the rest of the world can't use it!

So.. is there a way to define "closed" non-virtual inlineable functions for abstract types?

(p.s. I intend to answer this question myself but feel free to share your own answers!)

Upvotes: 2

Views: 3287

Answers (1)

Jayson Minard
Jayson Minard

Reputation: 86016

You say for "abstract types" and for an abstract class you can declare an inline function and it is automatically considered final.

abstract class BaseThing {
    inline fun foo() = "asdf"
}

Function foo can be called, but cannot be overridden in descendant classes. This results in the error:

'Foo' in 'BaseThing' is final and cannot be overridden

An interface on the other hand cannot have final methods. But you can write an extension function for the interface that acts almost the same.

interface TraitThing { }
inline fun TraitThing.foo() = "asdf"

But there is no protection or "closedness" because you can implement the method of the same name in an implementing class, and it will take precedence.

Upvotes: 5

Related Questions