Chapter 4 : Working with Classes in Kotlin (Android)

In this article, you will going to learn about classes and its properties in Kotlin.

But before moving to current topic, I explained Kotlin from beginning and you can find full list of previous tutorial at Kotlin page.

Classes

If you learnt any of Object Oriented Programming (OOP) language, you will be familiar with class and properties.

A class is a template or a blueprint for creating different objects which defines its properties and behaviours.

In Java, when you want to create any class, you require to declare a class, its constructor, getter and setter methods. All these to simple assign values to fields and fetch those values. This tedious job is reduced in Kotlin.

Java Kotlin

Its clearly visible, Java has 11 lines of code where Kotlin has 1. Writing such code is much enjoyable and save our lots of time from writing non-productive codes.

If you notice, in Kotlin there is no public keyword added before class. In Kotlin, by default each class is public. So you can drop writing it.

Properties

As stated in definition of class, it contains fields and methods. Generally those data are private and you can not access it directly. You need to create probably a getter methods to access those data. In any OOP language, this combination is known as property. In Kotlin, it replace methods to fetch values or to set values.

You can declare property in two ways. If you declare it with val, it will be read-only and if with var it will be mutable. You can modify it at any time.

Whenever you are declaring property, it will generates a field, a getter or a setter (based on declaration). Below is example by which you can create object of Student class and access its properties.

Custom accessor

Suppose that, you declared a property and want to write your custom logic to return result. This is possible with custom accessor. In our example, let say we want to know whether student is adult or not. Then we don’t need to store any extra property in class but we can do it with a simple way.

In this method, we defined isAdult property which will return result by checking whether age is greater then 18 or not. Note that, you need to declare method with val keyword otherwise it will give you an error.

Summary

In this article, you learnt how to declare a class and its properties. You got knowledge about getter and setter properties of Kotlin. You can also now declare your custom property method to return result based on custom logic.

Don’t forget to share this article and your feedback.

Protected by Copyscape

Share on Facebook12Share on Google+13Tweet about this on TwitterShare on LinkedIn0Share on Reddit0Pin on Pinterest0Share on Tumblr0Email this to someone