Wednesday, 20 December 2017

Kotlin: getters & setters to properties

In my previous post, I explained how to define properties, in addition to defining, we can add getter and setter methods to the properties.

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

PropertyType, getter and setter are optional while defining a property.

HelloWorld.kt
class Employee {
 var name: String = "Krishna"
  get() = field
  set(value) {
   field = value
  }

 var age : Int = 28
  get() = field
  set(value) {
   field = value
  }

 val orgID = "ORG1234"

}

fun main(args: Array<String>) {
 var emp = Employee()

 println("name : ${emp.name}")
 println("age : ${emp.age}")
 println("orgID : ${emp.orgID}")
}

Output
name : Krishna
age : 28
orgID : ORG1234

As you notify the code, I used ‘field’ identifier to refer backing field. By convention setter method takes ‘value’ as argument name, you can use any name.

Why do I require getter and setter methods?
Getter and setter methods are used to transform/validate the the data before sending/setting the information.

         var age : Int = 28
                 get() = field
                 set(value) {
                          if(value < 0 || value > 100)
                                  field = 3
                 }

For example, in the above snippet, setter method validate the age before setting it to the property age. If user sets the age to <0 (or) > 100, age will be set to 3. Find the below working application.


HelloWorld.kt
class Employee {
 var name: String = "Krishna"
  get() = field
  set(value) {
   field = value
  }

 var age: Int = 28
  get() = field
  set(value) {
   if (value < 0 || value > 100)
    field = 3
  }

 val orgID = "ORG1234"

}

fun main(args: Array<String>) {
 var emp = Employee()

 println("name : ${emp.name}")
 println("age : ${emp.age}")
 println("orgID : ${emp.orgID}")

 emp.age = -100
 println("\nAfter setting the age to -100")

 println("name : ${emp.name}")
 println("age : ${emp.age}")
 println("orgID : ${emp.orgID}")
}

Output
name : Krishna
age : 28
orgID : ORG1234

After setting the age to -100
name : Krishna
age : 3
orgID : ORG1234

Kotlin provides default getter and setter methods for mutable (Properties defined with var keyword) properties, where as it provides only getter method for immutable (Properties defined with val keyword) properties.

var name = "Krishna" //  has type String and a default getter and setter
val orfID = "orf1234" // has type String and a default getter





Previous                                                 Next                                                 Home

No comments:

Post a Comment