Home / Android / Kotlin :- Properties

Kotlin :- Properties

One of the nice function in kotlin is there are not any fields, like java. Any variable created in kotlin are homes by means of default with inside implementations of it’s accessors.

What are Fields and Properties in Java?

public elegance Employee 

Consider the category Employee which has worker identification and title and they’re non-public to the category and they’re regarded as as fields, so fields are principally the state or say inside variable the category makes use of.

But, while you upload getter and setter (accessors) for a similar, it turns into a belongings. Now, the fields describes the category and may also be accessed by way of it’s accessors.

So, in java to transform a box to a belongings you need to specify the accessors.

Coming again to Kotlin

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

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

elegance Employee 

What occurs below the hood?

Kotlin additionally creates it’s accessors by means of default.

In above Employee elegance, when title is initialized with “steve”, the use of = operator, internally set(price) means is named and every time this belongings is accessed the get() is invoked internally. And the similar occurs for identification as neatly, however because it’s immutable, kotlin best creates it’s getter and setter isn’t created.

amusing major(args:Array<String>)

The benefit of that is you don’t have to write down get() and set(), you’ll at once name title = “steve” and emp.title as an alternative of doing emp.getName() and emp.setName(“john”) in kotlin. Things turns into a lot more uncomplicated to code in kotlin.

The nice maintain that is on the subject of interoperability with java.

public elegance JavaMagnificence 

Now, when the Kotlin Employee elegance is named from Java elegance, it is going to be known as the use of the getters and setters which was once created internally by means of kotlin. worker.getName() and worker.setName(“John”)



Leave a Reply

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


%d bloggers like this: