KotlinTips: private, protected, and internal methods in Interfaces

Takumi WADA
2 min readJul 15, 2021
private, protected, and internal methods in Interfaces

Have you ever wanted to define private, protected, and internal methods for your Kotlin interface?

But even if you try to define it normally, you will get a compile error.
Here are some useful techniques in such cases.

TL;DR

You can define private, protected, and internal methods for interface in these ways.

interface Interface {
fun publicMethod() {
privateMethod()
}
private fun privateMethod() = Unit
fun Interface.protectedMethod()
}

internal fun Interface.internalMethod() = Unit

See below for a description of each.

How to define a private method in Interfaces

You can actually define a private method.
It can only be called from the default implementation of the public method.

interface Interface {
fun publicMethod() {
privateMethod()
}
private fun privateMethod() = Unit
}

Define a protected method in Interfaces

The protected method is defined within Interfaces as an extension function of Interfaces.
Basically, it can be called in the class that implements Interface.

interface Interface {
fun Interface.protectedMethod()
}
class Implementation : Interface {
override fun Interface.protectedMethod() = Unit

init {
protectedMethod()
}
}

It is not a fully protected method with the following exceptions:
The protected method can be called from outside the interface implementation class using with the scope function.

fun youCanCallProtectedMethodByWithTechnique() {
with(Implementation()){
protectedMethod()
}
}

Define an internal method in Interfaces

The internal method is defined outside the interface as an extension function of the interface.
Visibility is similar to a regular internal method.

interface Interface
internal fun Interface.internalMethod() = Unit
class Implementation : Interface {
init {
internalMethod()
}
}
fun methodInSameModule() {
Implementation().internalMethod()
}
fun methodInOtherModule() {
// Compile error! internalMethod is unresolved reference
Implementation().internalMethod()
}

Conclusion

Let’s enjoy Kotlin life! 🍻

--

--