Kotlin Setter and Getter tutorials with examples

This tutorial explains How to generate a Kotlin property setter and getter with examples.

Setter and getter are methods for a given property or a field in Kotlin classes The setter method sets the values to a property. The getter method gets or returns property value.

How to generate Setter and Getter in Kotlin

Kotlin declares the variables or fields using val and var.

var is used for mutable variable declaration, which can be changed later val is used for immutable variables, that can not be modified.

  • var field example By default, Kotlin generates a setter and Getter for every property declared in a class.

The default modifier for these setters and getter are public

For

class Employee {
    var name: String = ""
}

It generates the following setter and getter by default

class Employee {
    var name: String = ""
    get() {
        return field
    }
    set(value) {
        field = value
    }
}

Here is an example to call setter and getter

fun main() {
  val emp = Employee()
    // calling setter
    emp.name = "John"
    // calling getter
    println(emp.name)
}
class Employee {
    var name: String = ""
    get() {
        return field
    }
    set(value) {
        field = value
    }
}

if you don’t have a custom implementation in Setter and Getter functions, You can skip writing it.

  • val field example

kotlin by default generates only getters for variables declared with val,

val variables are immutable, hence, setters are not allowed.

fun main() {
  val emp = Employee()
     // calling getter
    println(emp.name)
}
class Employee {
    val name: String = ""
    get() {
        return field
    }

}

if you try to add a setter for the val variable, It throws the below message

Val cannot be reassigned A ‘val’-property cannot have a setter Reassignment of a read-only property via backing field

Public getter and Private Setter in Kotlin

You can customize the access modifier for these functions.

Here is an example public getter and private setter

var name: String = "John"
    get() {
        return name
    }
   private set(value) {
        name = value
    }