TExcelTAD
Home › Kotlin › Kotlin Visibility Modifiers

Kotlin Visibility Modifiers

Visibility modifiers control who can see and use a class, function or property. Hiding internal details — encapsulation — means other code can only use your class the way you intended, and you can change the internals later without breaking anyone.

The four modifiers

Modifier Class member is visible… Top-level declaration is visible…
public (default) everywhere everywhere
internal inside the same module inside the same module
protected inside the class and its subclasses — (not allowed)
private inside the class only inside the same file

A module is a set of files compiled together: a Gradle module, a Maven project, an IntelliJ module.

Note: Unlike Java, Kotlin's default is public, and there's no "package-private" level. internal is the closest equivalent.

private members

kotlin · try it yourself
class PiggyBank {
    private var coins = 0

    fun insert(n: Int) {
        require(n > 0) { "Insert at least one coin" }
        coins += n
    }

    fun shake() = if (coins > 0) "clink clink" else "silence"
}

fun main() {
    val bank = PiggyBank()
    println(bank.shake())
    bank.insert(5)
    println(bank.shake())
}
silence
clink clink

From outside, nobody can set coins to a negative number — they must go through insert, which validates the input. Accessing the private property is a compile error:

kotlin · try it yourself
class PiggyBank {
    private var coins = 0
}

fun main() {
    val bank = PiggyBank()
    bank.coins = 1000
}
File.kt:7:10: error: Cannot access 'var coins: Int': it is private in 'PiggyBank'.

Private setters

Often you want a property that everyone can read but only the class can change. Give the setter its own, narrower visibility:

kotlin · try it yourself
class Download(val file: String) {
    var progress = 0
        private set

    fun advance(step: Int) {
        progress = minOf(100, progress + step)
    }
}

fun main() {
    val d = Download("movie.mp4")
    d.advance(40)
    d.advance(70)
    println("${d.file}: ${d.progress}%")
}
movie.mp4: 100%

protected

protected members are hidden from the outside world but available to subclasses:

kotlin · try it yourself
open class Vehicle(protected val wheels: Int) {
    protected fun describeWheels() = "$wheels wheels"
}

class Bike : Vehicle(2) {
    fun info() = "A bike has ${describeWheels()}"
}

fun main() {
    println(Bike().info())
}
A bike has 2 wheels

Exposing read-only views

A common Kotlin idiom: keep a mutable collection private and expose it as a read-only type.

kotlin · try it yourself
class Playlist {
    private val _songs = mutableListOf<String>()
    val songs: List<String> get() = _songs

    fun add(song: String) {
        if (song !in _songs) _songs.add(song)
    }
}

fun main() {
    val p = Playlist()
    p.add("Blue")
    p.add("Yellow")
    p.add("Blue")
    println(p.songs)
    println(p.songs.size)
}
[Blue, Yellow]
2

Callers can read songs, but a List has no add function, so all changes must go through Playlist.add, which prevents duplicates.

Private constructors

class Token private constructor(val value: String) hides the constructor, so instances can only be made by functions inside the class (usually in a companion object — see the previous chapter).

Tip: Start with private and widen visibility only when something outside really needs access. It's easy to make something more visible later; making a public API private breaks callers.

Test yourself

What is the default visibility in Kotlin?

  1. private
  2. internal
  3. protected
  4. public

Where is a private top-level function visible?

  1. Everywhere
  2. In the same module
  3. In the same file
  4. Nowhere

How do you make a property publicly readable but only changeable inside the class?

  1. val with private get
  2. var with private set
  3. protected var
  4. internal val