Search code examples
kotlinvisibilityinternals

How can I access the internal members from a different module in Kotlin?


In Kotlin when applying "internal" to the member function of a public class, it is only visible inside the module.

In the case that there are core modules, and another module (call it outermodule) which has a class derived from the class defined in the core module.

Core module

package com.core

class BaseClass {
   internal fun method_internal() {...}
   public fun method_public() {...}
}

In the core module, the method_internal() can be accessed outside the BaseClass.

In the app, whoever has dependency on the core module, the BaseClass can be used in the app, but in the app it cannot see the internal method_internal(). That is the internal behavior wanted.

In another module (the outermodule) it has a class which is derived from the BaseClass.

outermodule

package com.outermodule

class DerivedClass : BaseClass {
......
}

In the outermodule it can use the method_public() from DerivedClass, but it can't access the method_internal().

And it cannot make the method_internal as protected since it should allow access in everywhere in the core module.

How can I make the method have internal visibility in one module, but at least be able to accessed from derived classes in other modules?


Solution

  • It isn’t pretty, but you can create two functions.

    open class BaseClass {
        protected fun foo() {
            println("foo!")
        }
    
        internal fun fooInternal() = foo()
    
    }