Properties – first-class citizens

Each class contains different attributes. The Person class, for example, contains the name, age, and height attributes. When a Person class is declared in Java or another programming language, these attributes are called fields of the class. When these fields are accessed by their corresponding getter and setter methods, they are called properties. To understand this concept in detail, create a Person class in Java, as follows:

public class Person {

String name;
int age;
double height;

Person(String n, int a, double h){
name = n;
age = a;
height = h;
}

public double getHeight() {
return height;
}

public void setHeight(double height) {
this.height = height;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

In this example, all attributes contain get and set methods. The name attribute is a field that will be turned into a property when the getName and setName methods are assigned to it for reading and writing purposes. A class may contain several different fields, and each field must have one or two corresponding methods to turn it into property. This approach not only adds unwanted boilerplate code, it also makes it harder to maintain the code. In Kotlin, classes don't contain fields; by default each attribute is a property of a class. Instead of interacting with fields by getter or setter methods, we can directly access the class properties. Kotlin provides all accessor functions under the hood. See the following example:

class Person (val name: String, var age: Int, var height : Double)
fun main(args: Array<String>) {
val person = Person("Abid", 40, 5.10)
val value = person.name
person.height = 6.0
println("name ${person.name}, age ${person.age}, height {person.height}")
}

In IntelliJ IDE, go to Tools | Kotlin | Show Bytecode, press the Decompile button, and verify the Kotlin-generated Java code. We can see the automatically generated functions for each property: getName for the name property, getAge and setAge for the age property, and getHeight and setHeight for the height property.

Kotlin will generate a getter function if the property is declared with the val keyword, meaning it is immutable. If the property is declared with the var keyword, however, meaning it is mutable, Kotlin will generate both getter and setter functions.

Each member variable of the class is a property by default and the properties of the class are first-class citizens. If we compare Java  and Kotlin code side by side, we can appreciate the power of Kotlin. Over 30 lines of code in Java is turned into a single line in Kotlin.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.181.252