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.internalis the closest equivalent.
private members
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:
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:
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:
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.
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
privateand 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?
- private
- internal
- protected
- public
Where is a private top-level function visible?
- Everywhere
- In the same module
- In the same file
- Nowhere
How do you make a property publicly readable but only changeable inside the class?
- val with private get
- var with
private set - protected var
- internal val