Kotlin - Class Visibility modifiers

Introduction

There are four visibility modifiers: public, internal, protected, and private.

If no modifier is given, then the default is used, which is public.

Private

Any top-level function, class, or interface that is defined as private can only be accessed from the same file.

Inside a class, interface, or object, any private function or property is only visible to other members of the same class, interface, or object:


class Person { 
    private fun age(): Int = 21 
} 

Here, the function age() would only be invokable by other functions in the Person class.

Protected

Top-level functions, classes, interfaces, and objects cannot be declared as protected.

Any functions or properties declared as protected inside a class or interface are visible only to members of that class or interface, as well as subclasses.

Internal

Internal deals with the concept of a module, which is defined as a Maven or Gradle module or an IntelliJ module.

Any code that is marked as internal is visible from other classes and functions inside the same module.

Effectively, internal acts as public to a module, rather than public to everyone:

internal class Person { 
   fun age(): Int = 21 
}