Visibility Modifiers
Discover how visibility modifiers in Kotlin control access to class members.
Introduction to visibility
When we design our classes, we prefer to expose as little as possible. If there is no reason for an element to be visible, we prefer to keep it hidden.
Visibility defines where an element can be used. If an element is not visible, it cannot be used.
This is why if there is no good reason to have a less restrictive visibility type, it is good practice to make the visibility of classes and elements as restrictive as possible. We do this using visibility modifiers.
Visibility modifiers for class members
For class members, these are the four visibility modifiers we can use:
public
(default): Visible everywhere for anyone who can see the declaring classprivate
: Visible inside this class onlyprotected
: Visible inside this class and in subclassesinternal
: Visible inside this module for anyone who can see the declaring class
Visibility modifiers for top-level elements
Top-level elements have three visibility modifiers:
public
(default): Visible everywhereprivate
: Visible inside the same file onlyinternal
: Visible inside this module
Module vs. package
Note that a module is not the same as a package. In Kotlin, a module is defined as a set of Kotlin sources that are compiled together. This might mean:
A Gradle source set
A Maven project
An IntelliJ IDEA module
A set of files compiled with one invocation of an Ant task
Code examples
Let’s see some examples, starting with the default visibility, which makes elements visible everywhere and can be explicitly specified using the public
modifier.
Default visibility (public
)
To ensure the correct execution of this code, follow these steps:
Copy the
main()
function from theMain.txt
file and paste it intoFile1.kt
. Then, click the “Run” button to view the expected output.After step 1, remove the copied code from the
Main.txt
file inFile1.kt
. Paste this code intoFile2.kt
and click the “Run” button to see the expected output.
Points to remember:
If the
main()
function is present in bothFile1.kt
andFile2.kt
, the code will not work as intended, resulting in errors.Also, errors will occur if no
main()
function is defined in eitherFile1.kt
orFile2.kt
as instructed in steps 1 and 2.
Get hands-on with 1400+ tech skills courses.