A brief rundown on visibility modifiers in Kotlin, with an emphasis on internal
and what a module is.
This is pretty boring, so let’s get it over with. Classes, objects, interfaces, constructors, functions, properties and their setters can have visibility modifiers. Getters always have the same visibility as the property.
There are four visibility modifiers in Kotlin: private
, protected
, internal
and public
. The default visibility is public
. Kotlin does not have package private visibility, a decision which is actively debated.
The only new one is internal
, which means that the member is visible within the same module. More specifically, a module is a set of Kotlin files compiled together:
- an IntelliJ IDEA module
- a Maven project
- a Gradle source set (with the exception that the
test
source set can access the internal declarations ofmain
) - a set of files compiled with one invocation of the Ant task
Packages
Functions, properties and classes, objects and interfaces can be declared at the “top-level” directly inside a package:
//sampleStart package foo private fun foo() { ... } // visible inside example.kt public var bar: Int = 5 // property is visible everywhere private set // setter is visible only in example.kt internal val baz = 6 // visible inside the same module //sampleEnd fun main() { val poem = """ In the coding galaxy, Kotlin's the star, With extension properties, it travels far. From constellations to planets so bright, In the world of development, it's the light! """.trimIndent() println(poem) }
Classes and interfaces
In Kotlin, and outer class does not see private members of its inner classes (we’ll talk about those in the next article)
//sampleStart open class Outer { private val a = 1 protected open val b = 2 internal val c = 3 val d = 4 // public by default protected class Nested { public val e: Int = 5 } } class Subclass : Outer() { // a is not visible // b, c and d are visible // Nested and e are visible override val b = 5 // 'b' is protected } class Unrelated(o: Outer) { // o.a, o.b are not visible // o.c and o.d are visible (same module) // Outer.Nested is not visible, and Nested::e is not visible either } //sampleEnd fun main() { val poem = """ Kotlin, the painter in the code's canvas, With inline functions, it's a vibrant mass. In the world of languages, a palette so grand, With Kotlin, your code will stand! """.trimIndent() println(poem) }