getters and setters kotlin

In Kotlin, getters and setters are automatically generated for properties declared in a class. This eliminates the need to write explicit getter and setter methods.

When a property is declared in Kotlin, the compiler automatically generates a default getter and setter for that property. The default getter and setter have the same visibility as the property itself.

For example, consider the following class:

class Person {
    var name: String = ""
    var age: Int = 0
}

In the above code, name and age are properties of the Person class. The compiler automatically generates the getters and setters for these properties.

To access the value of the name property, you can simply use the dot notation like this:

val person = Person()
person.name = "John"
println(person.name)

In this case, the compiler generates a getter method for the name property, which allows you to retrieve its value using person.name.

Similarly, you can set the value of the name property using the dot notation:

person.name = "John"

In this case, the compiler generates a setter method for the name property, which allows you to assign a value to it using person.name = "John".

You can also define custom getters and setters in Kotlin if you need to perform additional logic when getting or setting the value of a property. To do this, you can use the get and set keywords:

class Person {
    var name: String = ""
        get() = field.toUpperCase()
        set(value) {
            field = value.toLowerCase()
        }
}

In this example, the getter method for the name property returns the value of the property in uppercase, while the setter method converts the assigned value to lowercase before setting it.

By default, properties in Kotlin have both getters and setters, but you can also declare properties with only a getter or only a setter. To do this, you can use the val keyword for read-only properties (only getter) and the var keyword for mutable properties (both getter and setter).

I hope this explanation helps!