https://kotlinlang.org logo
#getting-started
Title
# getting-started
l

Loney Chou

09/29/2023, 3:18 AM
After searching for the answer, I still cannot grasp the reason why "functions within interfaces cannot be protected". I know Java doesn't allow this, but Kotlin could somehow lower the restriction (just like this proposal), no? My use case is that I need to define an interface that has a lot of default functions (they should be overriddable) delegated to an abstract function, and this function should be considered as implementation. Now that both internal and private are on the plate, where is protected?
x

xoangon

09/29/2023, 8:13 AM
Neither
protected
nor
private
are allowed in interfaces, and that's something that makes sense. An interface is a contract that doesn't get into implementation details. Both
private
and
protected
functions are part of an implementation. I recommend you read this Medium post about interfaces
r

Ronny Bräunlich

09/29/2023, 8:52 AM
From my point of view, if you must delegate to some internal implementation in an interface you should abstract it into another class (like Strategy pattern). Something like this:
Copy code
interface Foo {

    val inner: OtherFoo

    fun doSomething() {
        println("foo")
        inner.doSomething()
    }
}
l

Loney Chou

09/29/2023, 9:30 AM
Thanks for your response. 🤝 > Neither
protected
nor
private
are allowed in interfaces. >
private
is allowed in interfaces. The only reason I saw so far is "you can share logic for default functions", but with top level functions (even in Java you could make another util class), it makes no sense to have them inside interfaces (on the language level).
x

xoangon

09/29/2023, 11:33 AM
Oh, you’re right @Loney Chou. You can define
private
functions in interfaces. The correct statement would be: > You can’t declare
private
or
protected
abstract methods/accessors in an interface