Sobes.tech
Junior

How is encapsulation implemented in Kotlin?

sobes.tech AI

Answer from AI

Encapsulation in Kotlin is achieved through access modifiers and properties.

Access modifiers:

  • public: accessible from anywhere (default).
  • internal: accessible within the same module.
  • protected: accessible in its class and subclasses.
  • private: accessible only within the class where it is declared.

Properties are used to control access to class data. They can have getters and setters, which can be overridden to add logic when reading or writing the value.

class Person {
    // Private field, accessible only within the class
    private var _name: String = ""

    // Property with a public getter and a private setter
    var name: String
        get() = _name
        private set(value) {
            _name = value
        }

    // Public function to set the name, controlling input
    fun setName(newName: String) {
        if (newName.isNotBlank()) {
            name = newName
        } else {
            println("Name cannot be blank")
        }
    }
}

fun main() {
    val person = Person()
    person.setName("Alice") // Using controlled method to change
    println(person.name)    // Reading value through getter
    // person.name = "Bob"   // Compilation error, setter is private
}
How is encapsulation implemented in Kotlin? — Kotlin - sobes.tech