Kotlin basics: visibility modifiers. public, internal , protected and private.

Hugo Matilla
2 min readJun 13, 2018

--

“Man on a safari expedition looking through binoculars” by Louis Blythe on Unsplash

Visibility modifiers control which declarations are visible from others.

public: default

The public modifiers means that the declarations are visible everywhere.

In Kotlin the default visibility modifier is public while in Java is package-private. This modifier does not exist in Kotlin.

internal

internal is an alternative to Java’s package-private. internal means that the declarations are visible inside a module.

A module in kotlin is a set of Kotlin files compiled together. modules can be: maven projects, gradle sets, files generated from an Ant task, or a IntelliJ IDEA module

internal provides real encapsulation for the implementation details, while in Java’s package-private encapsulation could be broken. External code can define classes in the package you are trying to protect.

private

With private declarations are only visible in the class as in Java but in Kotlin also in the file (top level declarations) where it is declared.

Another difference is that in Kotlin outer classes do not see private nested (or inner) classes

protected

Declarations are only visible in its class and in its subclassess

Note: Extension Functions

Extension functions don’t get access to its private or protected members.

You can only create an extension function of a public class

Summary

Here is a table from the Kotlin in Action book that summarises these modifiers.

--

--