Kotlin :- Properties

One of the good feature in kotlin is there are no fields, like java. Any variable created in kotlin are properties by default with internal implementations of it’s accessors.

What are Fields and Properties in Java?

public class Employee {
private long id;
private String name;
    public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getName() {
return name;
}

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

Consider the class Employee which has employee id and name and they are private to the class and they are considered as fields, so fields are basically the state or say internal variable the class uses.

But, when you add getter and setter (accessors) for the same, it becomes a property. Now, the fields describes the class and can be accessed via it’s accessors.

So, in java to convert a field to a property you have to specify the accessors.

Coming back to Kotlin

In kotlin every variable you create has it’s default internal implementation of assessors, i.e. it has default implementation of getters and setters.

Note:- The getters and setters are only created for mutable properties (var) and for immutable properties only getter is created.

class Employee {
var name = "Steve" // getter and setter is created
val id = 1 // only getter is created
}

What happens under the hood?

Kotlin also creates it’s accessors by default.

In above Employee class, when name is initialized with “steve”, using = operator, internally set(value) method is called and whenever this property is accessed the get() is invoked internally. And the same happens for id as well, but since it’s immutable, kotlin only creates it’s getter and setter is not created.

fun main(args:Array<String>){
var emp = Employee()
println(emp.name) // internally get() is called
emp.name = "John" // internally set(value) is called
println(emp.name)

println(emp.id)
emp.id = 2 // This will not work as immutable property can't be reassigned.
}

The good thing about this is you don’t have to write get() and set(), you can directly call name = “steve” and emp.name instead of doing emp.getName() and emp.setName(“john”) in kotlin. Things becomes much easier to code in kotlin.

The great deal with this is when it comes to interoperability with java.

public class JavaClass {
public static void main(String[] args) {
Employee employee = new Employee();
System.out.println(employee.getName());
employee.setName("John");
System.out.println(employee.getName());

System.out.println(employee.getId());

// Won't work
System.out.println(employee.setId()); // No, setter generated for the immutable property in kotlin.
}
}

Now, when the Kotlin Employee class is called from Java class, it will be called using the getters and setters which was created internally by kotlin. employee.getName() and employee.setName(“John”)

References

https://kotlinlang.org/docs/reference/properties.html