Subscribe our newsletter
Search
Close this search box.

Kotlin Setters and Getters

Latest posts
Get notified of the Latest Sport News Update from Our Blog
Share

In Kotlin, a getter is a method automatically generated to retrieve the value of a property, while a setter is a method generated to modify the value of a mutable property. Custom logic can be added to getters and setters if needed.

Getters:

Automatic Getter:

When you declare a property using var or val, Kotlin automatically generates a default getter. For val (read-only) properties, only the getter is generated

class Example {
    val readOnlyProperty: Int = 42  // Automatic getter is generated
}

To access the property:

val value = example.readOnlyProperty  // Accessing the property using the default getter

Custom Getter: A custom getter is a way to define how a property’s value should be calculated or retrieved when it is accessed. custom getter can be defined by using the get() method within the property declaration.

class Person(val firstName: String, val lastName: String) {
    // Custom getter for the fullName property
    val fullName: String
        get() {
            return "$firstName $lastName"
        }
}

fun main() {
    val person = Person("John", "Doe")
    println("Full Name: ${person.fullName}") // Full Name: John Doe
}

In this Example, When access the fullName get() will run and returns the fullname

Setters:

Automatic Setter:

For mutable properties declared with var, Kotlin generates both a getter and a setter. for val keyword kotlin only generated getters

class Example {
    var mutableProperty: Int = 42  // Automatic getter and setter are generated
}

To set the property:

example.mutableProperty = 54  // Setting the property using the default setter

Custom Setter: It is used to add custom logic that is executed when a property is assigned a new value. A custom setter is declared using the set() method within the property declaration. Here’s a simple example:

class Example {
    var customProperty: Int = 42
        set(value) {
            field = value * 2
        }
}

fun main() {
    var e1 = Example()
    println(e1.customProperty) // Output: 42

    
    //Setting the property using the custom setter
    e1.customProperty = 78    // Corrected line
    println(e1.customProperty) // Output: 156
}

In this example the customProperty has a custom setter that doubles the value assigned to it.

Related blogs

Nullam quis risus eget urna mollis ornare vel eu leo. Aenean lacinia bibendum nulla sed 

Subscribe for coding tips and tutorials!