Kotlin Visibility Modifiers

www.‮tfigi‬idea.com

In Kotlin, there are four visibility modifiers that can be used to control the visibility of a class, object, interface, constructor, property, function, or type alias:

  1. public: The default visibility modifier, which means that the declaration is visible everywhere in the project. You can also explicitly use the public modifier to make it clear.

  2. private: The declaration is only visible inside the class or file where it is declared.

  3. protected: The declaration is only visible inside the class and its subclasses.

  4. internal: The declaration is visible inside the module where it is declared. A module is a set of Kotlin files compiled together, which can be a single project, a library, or a set of related projects.

Here's an example of using visibility modifiers in a Kotlin class:

package com.example.myapp

class MyClass {
    public var publicProperty: Int = 0
    private var privateProperty: Int = 0
    protected var protectedProperty: Int = 0
    internal var internalProperty: Int = 0

    public fun publicFunction() {}
    private fun privateFunction() {}
    protected fun protectedFunction() {}
    internal fun internalFunction() {}
}

In this example, we have a class called MyClass with four properties and four functions, each with a different visibility modifier. The public property and function have the public modifier explicitly defined, but this is not necessary as it is the default. The private property and function are only visible inside the MyClass class. The protected property and function are only visible inside the MyClass class and its subclasses. The internal property and function are visible within the entire module where MyClass is defined.

It's important to use visibility modifiers to control access to your code and make it easier to reason about the behavior of your program. For example, you can use the private modifier to hide implementation details that should not be exposed to other parts of the program, or the protected modifier to make sure that only subclasses can access certain properties or methods.