Make a function execute only in Kotlin interfaces?

Viewed 119

If I have an interface, is there any easy way I can declare a function to make it a public member, but non-overridable? Meaning, it would be exclusively callable and could not be set or overridden by its descendants

interface IFoo {
    fun ExecuteOnly(){
       // Do Something
    }
}
4 Answers

I read a book recently by CommonsWare where this situation was described. and I quote it from there:

"... As a result, anything in an interface hierarchy is permanently open , until you start implementing the interfaces in classes. If that is a problem — if you have some function that you really want to mark as final — use abstract classes, not interfaces..."

You can define an extension function on the interface.

fun IFoo.executeOnly() {

}

It will still be possible for someone to define a member function with that name in a class implementing IFoo but the intention is quite clear. And anyway when using an object via a IFoo reference the IFoo extension will be chosen.

No, you cannot. That's not how Kotlin's interface is implemented.

You can use an abstract class instead

abstract class Foo {
    fun executeOnly(){
       // Do Something
    }
}

Ofcourse You Can... Actually there is not much difference bw kotlin interfaces and abstract classes... simply add a body and a private modifier..

interface MyInterface {
    
    fun triggerTakeMe(){
        takeMe()
    }
    
   private fun takeMe(){
        println("Taken")
    }
}

class MyClass : MyInterface 

fun main() {
    
    val obj = MyClass()
    obj.triggerTakeMe()

}
Related