Sunday, May 13, 2018

Kotlin-Properties and Fields

Before discussing Fields and Properties in Kotlin let's recall Java and try to understand it.
Java Class
public class User {                                                                        
    private String id;
    private String name;
    public User (String id, String name) {
        this.id = id;
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

As you can see User class which has user id and name. They are private to the class and they are considered as fields in Java, so fields are basically the state. But, when you generate getter and setter (accessors) for the fields it's become a property. Now, the fields describe the class and can be accessed via its accessors.


 
Back to Kotlin.

Introduction of Kotlin.

One of the good thing with kotlin is that there are no fields. Any variable created in kotlin are properties by default with internal implementations of its accessors. In kotlin, every variable of the class has its default implementation of getters and setters.
Kotlin compiler creates getters and setters for mutable properties (var) and for immutable properties create getter only.
Kotlin Class

class User {
    var name = "Sun" // getter and setter is created
    val id = 1 // only getter is created
}
In above User class, when the name is initialized with “Sun”. Compiler internally set(value) method is called and whenever this property has accessed the get() is invoked internally. And the same happens for id as well, but since it’s immutable, kotlin only creates its getter and setter is not created.

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


The great thing about this is it comes to interoperability with java.

Java Class
ppublic class JavaClass {
    public static void main(String[] args) {
        User user= new User();//Kotlin 
        System.out.println(user.getName());
        user.setName("Sun");
        System.out.println(user.getName());
        System.out.println(user.getId());        
    }
}

Now, when the Kotlin User class is called from Java class. It will be called using the getters and setters which was created internally by kotlin. 

Let’s understand what these identifiers


1. Value:- We use value as the name of the setter parameter. This is the default convention in Kotlin but you’re free to use any other name if you want. The value parameter contains the value that a property is assigned to. For example, when you write a user.name = "sun", the value parameter contains the assigned value “sun”.


2. Backing Field (field):-  is an autogenerated field for property which can be used inside the accessors(getter or setter) and will be present if it uses the default implementation of at least one of the accessory, or if a custom accessor references it through the field identifier. 


What is the need for Backing field?


This backing field is used to avoid the recursive call of an accessor which ultimately prevents the StackOverflowError.

Kotlin Class
public class User{
    var id: Int = 1
        get() = id
        set(value) {
            this.id= value
        }
}
The above code is calling the getter in a recursive manner. If we try to get the value of id. when we call ‘id’, it calls the getter again inside the getter which might end with a StackOverflowError.

Similar way, when we try to set the value of id it calls the same setter in a recursive way as ‘this.id’ calls the setter again from inside a setter method.


How to use Backing field?


When using custom accessors. For these purposes, Kotlin provides an automatic backing field which can be accessed using the field identifier.


Replace the variable with the keyword field inside getter and setter

Kotlin Class
public class User{
    var id: Int = 1
        get() = field
        set(value) {
            field = value
        }
}
Limitations while using Backing field.

1. The field identifier can only be used in the accessors of the property.

2. A backing field will be generated for a property if it uses the default implementation of at least one of the accessors, or if a custom accessor references it through the field identifier.

For example, in the following case there will be no backing field:

Kotlin Class
public class User{
   val isEmpty: Boolean //immutable
    get() = this.size == 0
}



Previous                                                                       Next

I tried my best to explain all the concepts. But if you still have any doubt, please feel free to clarify that in the comment section below.
Share:

Get it on Google Play

React Native - Start Development with Typescript

React Native is a popular framework for building mobile apps for both Android and iOS. It allows developers to write JavaScript code that ca...