How to Getters and Setters in Kotlin

Kailash Vaviya Feb 15, 2024
  1. Getters and Setters in Kotlin
  2. Use Kotlin Set as a Private Modifier
  3. Custom Getters and Setters in Kotlin
How to Getters and Setters in Kotlin

This article will introduce getters and setters in Kotlin and their use. We will also demonstrate some examples to understand the work of getters and setters.

Getters and Setters in Kotlin

In general programming, getters help fetch the value of a property. Similarly, setting a property’s value is done with setters.

Kotlin getters and setters are auto-generated. Hence, we do not need to create them separately for our programs.

So, if we write,

class Student {
    var Name: String = "John Doe"
}

The code above is equivalent to the following Kotlin program.

class Student {
    var Name: String = "John Doe"
    get() = field
    set(para) {
        field = value
    }
}

Hence, when we instantiate an object of a class, Student in the example above, and initialize a property, the setter function will automatically set the value to the parameter accessed using the getter function.

Mutable and Immutable Properties in Kotlin

In Kotlin, we can create two types of properties: mutable and immutable.

The mutable properties are declared using changeable variables denoted by the keyword var. The immutable keywords are expressed using the non-changeable variables marked by the keyword val.

Another difference between these properties is that a read-only or immutable property does not create a setter, as it does not need to change anything.

Here is an example using both get() and set() functions in Kotlin based on the syntax above.

fun main(args: Array<String>) {
    val v = Student()
    v.Name = "John Doe"
    println("${v.Name}")
}

class Student {
    var Name: String = "defValue"

    get() = field

    set(defaultValue) {
        field = defaultValue
    }
}

Output:

Working of Default Getters and Setters in Kotlin

Use Kotlin Set as a Private Modifier

The default getters and setters have a public modifier. We can change this if we want to use the setter with the private modifier by using the private keyword.

By declaring a private setter, we can only set a value through a method within the class.

In this example, we will create an object for the Student class and access the Name property initially set to John Doe. Next, we will assign the name to Jane Doe through a function inside the class and reaccess it.

class Student () {
    var Name: String = "John Doe"
        private set

    fun randFunc(n: String) {
        Name = n
    }
}

fun main(args: Array<String>) {
    var s = Student()
    println("Initially, name of the student is: ${s.Name}")
    s.randFunc("Jane Doe")
    println("Now, name of the student is: ${s.Name}")
}

Output:

Using Setter With Private Modifier

Custom Getters and Setters in Kotlin

We can also make custom getters and setters in Kotlin. Here’s an example where we build custom get() and set() methods for a property.

class Student{
    var Name: String = ""
        get() {
            println("We are in Name property's get()")
            return field.toString()
        }
        set(defaultValue) {
            println("We are in Name property's set()")
            field = defaultValue
        }
    val ID: Int = 1013
        get(){
            println("We are in ID property's get()")
            return field
        }
}

fun main() {
    val stu = Student()
    stu.Name = "John Doe"
    println("The age of ${stu.Name} is ${stu.ID}")
}

Output:

Create and use Custom Getter and Setter in Kotlin

Kailash Vaviya avatar Kailash Vaviya avatar

Kailash Vaviya is a freelance writer who started writing in 2019 and has never stopped since then as he fell in love with it. He has a soft corner for technology and likes to read, learn, and write about it. His content is focused on providing information to help build a brand presence and gain engagement.

LinkedIn