2

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!)

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't know about inline in abstract classes! Great answer!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.