Tag Archives: kotlin tutorial

Data Class

While building any application, we often need to create classes whose primary purpose is to hold data/state. These classes generally contain the same old boilerplate code in the form of getters, setters, equals(), hashcode() and toString() methods.

Kotlin has a better solution for classes that are used to hold data/state. It’s called a Data Class. A Data Class is like a regular class but with some additional functionalities.

With Kotlin’s data classes, you don’t need to write/generate all the lengthy boilerplate code yourself. The compiler automatically generates a default getter and setter for all the mutable properties, and a getter (only) for all the read-only properties of the data class. Moreover, It also derives the implementation of standard methods like equals(), hashCode() and toString() from the properties declared in the data class’s primary constructor.

Example Customer data class


Syntax of data class

Continue reading Data Class

Follow and like us:

Getters and Setters

Getters and Setters are used to effectively protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Getters and setters are also known as accessors and mutators, respectively.

Accessing properties directly is not a good practice.

Sometimes we need to check the value in case of an invalid input, or do some other data validation or calculation before assigning or accessing the property value.

Continue reading Getters and Setters

Follow and like us:

Abstract Class

In Kotlin, abstract class is declared using the abstract keyword in front of class. An abstract class can not instantiated means we can not create object for the abstract class.

Important points

      • We can’t create an object for abstract class.
      • All the variables (properties) and member functions of an abstract class are by default non-abstract. So, if we want to override these members in the child class then we need to use open keyword.
      • If we declare a member function as abstract then we does not need to annotatate with open keyword because these are open by default.
      • An abstract member function doesn’t have a body, and it must be implemented in the derived class.
      • An abstract class can contain both abstract and non-abstract members.

Continue reading Abstract Class

Follow and like us:

Class

A class is a blue print defined which groups functions and properties. Classes in Kotlin are defined using the keyword class followed by the class name. The body goes inside the curly braces.


Syntax of class in Kotlin

An instance of the class is instantiated in the following way


instance of the class

Contrary to Java, new isn’t a keyword in Kotlin.


new is not a keyword

Continue reading Class

Follow and like us: