Kotlin Properties, Getters and Setters

Before we jump on and discuss about Kotlin Getters and Setters it is important for us to understand the basic working of Properties in Kotlin.

Kotlin Properties

Properties are part and parcel of kotlin. Definition of properties in kotlin is done in the same way as declaration of another variable. Any property defined in Kotlin can be either a mutable or immutable, these differ on the basis of keyword used during declaration. We can declare mutable keywords using “var” keyword and immutable keywords using “val” keyword.

A typical syntax of Property is as follows:

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

Key Point to note here is the optional use of getters and setters.

var a: Int = 0

Here, “a” is taken as variable, with value as 0. In case when the property initializer mentions the value, we can skip explicit use of property type.

Let’s have a look at val or read only variables. A val is a read only variable and is referred as an immutable type. Since it is immutable it is quite evident that it cannot be used to set another value once assigned.

fun main(args: Array<String>) { 
  	var a: Int = 10
   	 val b: Int = 20
    a = 2 // Variables can be assigned any number of times.
    b = 0 // Val or immutable variables cannot be reassigned and hence gives errors.
}

The above code gives the error as:

Val cannot be reassigned

Kotlin Getters and Setters

As it is evident from the name, getters are used get values and setters are used to assign or set values. Kotlin has auto generation of getters and setters unlike Java.

The below example explains:

class Greeting {
    var message: String = "Hello World!"
}

The above code is equivalent to the one with getters and setters as below:

class Greeting {
    var message: String = "Hello World!"
    get() = field     // getter
    set(value) {        field = value    }     // setter
}

When we instantiate the object of class Greeting “greetHW” and initialize the property message by passing value as “Hello World!”, it calls the setter and eventually sets the value.

If you wish to fetch the value of property message, we can do that by calling the get() method which returns the value of the property.

val greet = Greeting ()
    c.message = "Hello World!"   // Setting value using setter
    println(c.message)           // Getter Called

The output of the above code would be Hello World! which is returned by the getter of the message.

Let’s have a look at working prototype of the getters and setters:

class Greeting () { 
	var message: String = "Hello World!"
		private set 

	fun newFunc(str: String) { 
		message = str			 // Setter is called here
	} 
} 

fun main(args: Array<String>) { 
	var greet = Greeting() 
	println("Greeting Message is : ${greet.message}") 
	greet.newFunc("Getter & Setter Example") 
	println("Message Set by new Function is : ${greet.message}") 
}

Output:

Greeting Message is : Hello World!
Message Set by new Function is : Getter & Setter Example

In the example above the point to ponder was the use of private with the setter. Since the setter was declared as private hence it was not possible to set the value from outside the class. For the same purpose we created a new function which was used to set new value to the variable.

Defining Custom Getters and Setter in Kotlin

There can be cases, when we would have custom code to our getters and setters (For Example : to apply validation when trying to set a value, converting cases of values entered, counting total number of instances created). In such cases we can create custom getters and setters like in the example created below:

class LogInUser( userName: String, password: String) { 
  
    var user_name: String = userName 
        // Updated Getter or Customised Getter to convert the userName to Lowercase 
        get() { 
           return field.toLowerCase() 
        } 
    var password: String = password 
        //Password Custom Setter, to check length validation
        set(value){ 
            field = if(value.length > 6) value else throw IllegalArgumentException("Passwords is too small") 
        } 

} 
  
fun main(args: Array<String>) { 
    val user = LogInUser("User@kotlintutorialblog.com","Password") 
  
    println("${user.user_name}") 

    println("${user.user_name}") 
    println("${user.password}") 
 
      
    // Setting a small Password would give Exception as : IllegalArgumentException("Password is too small.")   
    user.password = "test"      
}

In the example above, we have created custom getter and setter to convert the user name to lower case to ensure smooth login. Also, the password is only set in the class if it meets the length requirements of 6 characters.

Output:

user@kotlintutorialblog.com
user@kotlintutorialblog.com
Password
Exception in thread “main” java.lang.IllegalArgumentException: Passwords is too small
at LogInUser.setPassword (File.kt:11)
at FileKt.main (File.kt:26)

From the output it is quite relevant that on setting of password of length 4 it gives an error. Also, note that the user name passed by the user has been converted to lower case irrespective of case user types in.

That was all about the concepts of Kotlin getters and setters, there’s still scope on how to use getters and setters in case of overriding which we will be seeing in the next tutorials. Till then keep reading and exploring.

Leave a Comment

Your email address will not be published. Required fields are marked *