Kotlin Getters and Setters Tutorial

In this section, we will learn what the getters and setters are and how to use them in Kotlin.

What are Getters and Setters in Kotlin?

The getters and setters are a way of controlling the value that can be get or set to a property of an object!

Basically, they are functions that will be invoked automatically when users try to interact with the target property (Either try to set or get a value from the property)

For example, let’s say there’s a property named weight in a class. Now we want to control the minimum value that could be assigned to this property to not be less than 10Kg, for example. So by adding a setter to the target property, we can control the input value to the property and alert users if they attempt to put values less than that and skip the incoming value.

Also, using the getter for a property, we can control how a value of a variable should return when someone is calling the property to take its value!

For example, you might have a property named firstName that is holding the name of a person. Now let’s say you want to add this message before the name of the person “The name is: “anytime someone calls for the value of the firstName variable.

So using a getter on a property, we can get early access to the value of that property and modify it the way we want and then return the result to the caller of that property.

Kotlin Getter Syntax:

This is how we can add a getter to a property:

var firstName:String

get(){

    return field

}

The getter function comes right at the next line of the place where we declare the target property.

So here, for example, the firstName property has a getter method, and it simply returns the value of the property whenever we call it.

If for example, we wanted to prefix the value of the variable with another value, we could do so like this:

var firstName:String

get(){

    return “The first name is: ${field}”

}

Note: the return data type of the getter must match the data type of the property itself! This means if the data type of property is String, for example, you can’t return a value of type Float or Int etc, from the get() function; It must be String.

Kotlin field Keyword

The keyword field you saw in the syntax above refers to the property that we’re setting a getter or setter for it. Basically, the field is equal to the name of the target property. But we don’t use the name of the property within its getter or setter because if we do so, it will create an infinite loop! For this reason, if we need to access the current property, we use the field keyword instead.

Example: creating getter in Kotlin

class Person {
    var firstName:String 
        get(){
            return "The first name is: $field"
        }
    var lastName:String

    constructor(firstName:String, lastName:String){
        this.firstName = firstName
        this.lastName = lastName
    }
}

fun main(){
    var prs  = Person("Jack","Bauer")
    println(prs.firstName)
    println(prs.lastName)
    
}

Output:

The first name is: Jack

Bauer

Here, as you can see, the firstName property has a getter function and it will be invoked whenever we try to access the current value of this property. Now within the body of the getter function of this property, we’ve changed the value by prefixing it with another string value.

Kotlin Setter Syntax

This is how we can set a setter for a property:

var firstName:String

set(value){

    field = value

}

To create a setter for a property, we start with the keyword set and a pair of parentheses with one parameter that we usually call value. Whenever we assign a value to a property, that value will be assigned as the argument of the set() function. So the `value` parameter will hold the value we are assigning to the target property.

Now, within the body of the setter, we can analyze this input value and see if it matches our requirements and if so, then we assign it to the target property using the field keyword.

Just like the getter that we set it in the next line of a property, the setter functions are also set right at the next line of the target property.

Also note that if you want to set the getter and setter both together for a property, you can put both of them under the target property one after the other as:

var firstName:String 
        get(){
            return "The first name is: $field"
        }
        set(value){
            if (value == "Unknown"){
                println("Sorry you can't put the value Unknown as first name!")
                field = "No-name"
            }else{
                field = value
            }
        }

Example: creating setter in Kotlin

class Person {
    var firstName:String 
        get(){
            return "The first name is: $field"
        }
        set(value){
            if (value == "Unknown"){
                println("Sorry you can't put the value Unknown as first name!")
                field = "No-name"
            }else{
                field = value
            }
        }
    var lastName:String

    constructor(firstName:String, lastName:String){
        this.firstName = firstName
        this.lastName = lastName
    }
}

fun main(){
    var prs  = Person("Jack","Bauer")
    println(prs.firstName)
    println(prs.lastName)
    
}

Output:

The first name is: Jack

Bauer

Note: here we’ve used a secondary constructor to initialize the firstName property. But if we didn’t have the secondary constructor, we had to initialize the properties that have setters set for them explicitly and this should’ve been done right at the declaration of that property! Again, because in this example, there’s a secondary constructor and the firstName variable is initialized there, we don’t need to initialize the property at its declaration time.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies