Setters & Getters

Setters & Getters

Hey, welcome again to my blog! Today, we shall learn more about Kotlin Setters & Getters and if you have missed any of my previous tutorials in this series, kindly check them out here.

What are Setters & Getters❓

image.png image.png In computer science, a mutator method is a method used to control changes to a variable. They are also widely known as setter methods. Often a setter is accompanied by a getter (also known as an accessor), which returns the value of the private member variable.

Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value

Classes have properties and these properties can either be mutable or immutable. To create setters, we use the var keyword.

The full syntax for declaring a property is as follows:

var <propertyName>[: <PropertyType>] [= <property_initializer>]
    [<getter>]

The initializer, getter, and setter are optional.

In Kotlin, a setter is used to set the value of any variable and a getter is used to get the value. Getters and Setters are auto-generated in the code. Let’s define a property ‘name‘, in a class, ‘Company‘.

The data type of ‘name‘ is String and we shall initialize it with some default value.

class Company {
var name: String = "Defaultvalue"
}

The above code is equivalent to this code:

class Company {
    var name: String = "defaultvalue"
        get() = field                     // getter
        set(value) { field = value }      // setter
}

We instantiate an object c of the class Company {…} When we initialize the name’property, it is passed to the setter’s parameter value and sets the field to value.

When we are trying to access name property of the object, we get field because of this code get() = field. We can get or set the properties of an object of the class using the dot(.) notation–

val c = Company()
c.name = "Kotlin is Made More Fun"  // access setter
println(c.name)           // access getter (Output: Kotlin is Made More Fun)

Kotlin Program of Default Setter and Getter

class Company {
    var name: String = ""
        get() = field        // getter
        set(value) {         // setter
            field = value
        }
}
fun main(args: Array<String>) {
    val c = Company()
    c.name = "Yeah, let's do this !"  // access setter
    println(c.name)           // access getter
}

Output :

Yeah, let's do this !

Value and Field Identifiers

We have noticed these two identifiers in the above program.

Value:

Conventionally, we choose the name of the setter parameter as value, but we can choose a different name if we want.

The value parameter contains the value that a property is assigned to. In the above program, we have initialized the property name as c.name = “Yeah, let's do this !”, the value parameter contains the assigned value “Yeah, let's do this !”.

Backing Field (field):

It allows storing the property value in memory possible. When we initialize a property with a value, the initialized value is written to the backing field of that property. In the above program, the value is assigned to field, and then, field is assigned to get().

Private Modifier

If we want the get method in public access, we can write this code:

var name: String = ""
    private set

And, we can set the name only in a method inside the class because of private modifier near set accessor.

Kotlin program to set the value by using a method inside a class.

class Company () {
    var name: String = "abc"
        private set

    fun myfunc(n: String) {
        name = n             // we set the name here
    }
}

fun main(args: Array<String>) {
    var c = Company()
    println("Name of the company is: ${c.name}")
    c.myfunc("Yeah, let's do this !")
    println("Name of the new company is: ${c.name}")
}

Output:

Name of the company is: abc
Name of the new company is: Yeah, let's do this !

Explanation:

Here, we have used private modifier with set. First, instantiate an object of class Company() and access the property name using ${c.name}. Then, we pass the name “Yeah, let's do this !” as a parameter in a function defined inside the class. The name property updates with a new name and access again.

Custom Setter and Getter

class Registration( email: String, pwd: String, age: Int , gender: Char) {

    var email_id: String = email
        // Custom Getter
        get() {
           return field.toLowerCase()
        }
    var password: String = pwd
        // Custom Setter
        set(value){
            field = if(value.length > 6) value else throw IllegalArgumentException("Passwords is too small")
        }

    var age: Int = age
        // Custom Setter
        set(value) {
            field = if(value > 18 ) value else throw IllegalArgumentException("Age must be 18+")
        }
    var gender : Char = gender
        // Custom Setter
        set (value){
            field = if(value == 'M') value else throw IllegalArgumentException("User should be male")
        }
}

fun main(args: Array<String>) {

    val geek = Registration("greatme@gmail.com", "Geeks@123", 25 , 'M')

    println("${geek.email_id}")
    geek.email_id = "newmail@mail.com"
    println("${geek.email_id}")
    println("${geek.password}")
    println("${geek.age}")
    println("${geek.gender}")

    // throw IllegalArgumentException("Passwords is too small")
    geek.password = "abc"   

    // throw IllegalArgumentException("Age should be 18+")
    geek.age= 5  

    // throw IllegalArgumentException("User should be male")
    geek.gender = 'F'        
}

Output:

greatme@gmail.com
newmail@mail.com
Geeks@123
25
M

To achieve the same thing in Python, you can use normal functions, property decorators pr property() function.

Using Normal Function in Python:

class Person:
    def __init__(self, age = 0):
        self._age = age

    # getter method
    def get_age(self):
        return self._age

    # setter method
    def set_age(self, x):
        self._age = x

AfroBoy = Person()

# setting the age using setter
AfroBoy.set_age(21)

# retrieving age using getter
print(AfroBoy.get_age())

print(AfroBoy._age)

Resources:
📌 Baeldung
📌 Kotlin Official Docs
📌 Geeks For Geeks

Conclusion:

Visit the links in the resource section to learn more and read more >>>

If you enjoyed this article, consider liking, sharing and subscribing:

Ronnie Atuhaire 😎