Visibility Modifiers in Kotlin

Vefa Can Beytorun
3 min readMar 9, 2023

--

Classes, objects, interfaces, constructors, and functions, as well as properties and their setters, can have visibility modifiers.

Introduction

Hello dear reader welcome to my article, I’m Vefa Can. Today I would like to talk about Visibility Modifiers in Kotlin. I hope my article is useful to you. Now lets start with “What is Visibility Modifiers”.

Visibility Modifiers

In Kotlin, visibility modifiers are used to control the visibility of classes, interfaces, functions, properties, and other declarations. The visibility modifier determines which parts of the code can access the declaration. Kotlin provides four visibility modifiers: public, private, internal, protected.

1) Public

This is the default visibility modifier, if you don’t use any visibility modifiers, Kotlin will automatically make that declaration public and it means that the declaration is visible everywhere. If a declaration is marked as public, it can be accessed from any module, package, or class.

As you can see, when assigning the “x” variable, we assign it as the default without using any words, but we used the public keyword to the “y” variable. Both variables are set to public!

2) Private

This modifier restricts the visibility of a declaration to its own class or file. If a declaration is marked as private, it can only be accessed from within the same file or class. It is not visible to other classes or files, even if they are in the same package.

As you can see, our function could not access the variables because the variables were set as private.

3) Internal

This modifier restricts the visibility of a declaration to its module. A module is a group of Kotlin files compiled together. If a declaration is marked as internal, it can be accessed from any class or file within the same module.

The function can access variables because they are in the same module.

4) Protected

This modifier restricts the visibility of a declaration to its own class and its subclasses. If a declaration is marked as protected, it can only be accessed from within the same class or any subclasses of the class. So we need Inheritance here. If you do not have enough information about Inheritance, you can check out my article about Inheritance.

As you can see, we were able to access protected variables by inheritance. If we didn’t use inheritance, the program would fail to compile.

Conclusion

As a result when you using visibility modifiers effectively, you can control the visibility of your code and ensure that it is accessible only where it needs to be, while keeping it hidden from other parts of your code or other modules.

Thank you for your attention. Have a nice day.

References

--

--