Junior
What is the access modifier 'internal' in Kotlin and how is it used?
sobes.tech AI
Answer from AI
The access modifier internal in Kotlin means that the declaration is visible within the same module. A module can be a set of Kotlin files compiled together, for example:
- Gradle module (source set).
- Maven module.
- Ant source set.
This is useful for hiding implementation details within a module, making them inaccessible to code from other modules.
internal can be used with:
- Classes
- Interfaces
- Objects
- Functions
- Properties
- Constructors
Example of usage:
// Module "module1"
package com.example.module1
internal class InternalClass {
internal fun internalFunction() {
// This code is visible only within module1
}
}
// This object is also visible only within module1
internal object InternalObject {
internal val internalProperty = "Internal value"
}
// Module "module1"
package com.example.module1
fun someFunctionInModule1() {
val internalCls = InternalClass() // Accessible
internalCls.internalFunction() // Accessible
println(InternalObject.internalProperty) // Accessible
}
// Module "module2"
package com.example.module2
import com.example.module1.InternalClass // Compilation error
import com.example.module1.InternalObject // Compilation error
fun someFunctionInModule2() {
// Cannot create an instance of InternalClass or access InternalObject
// val internalCls = InternalClass() // Not accessible
// println(InternalObject.internalProperty) // Not accessible
}
The main difference from public (visible everywhere), private (visible only within the class), and protected (visible within the class and its subclasses) is precisely the level of visibility by modules.