Classes
Explore creating classes in Kotlin, including defining primary constructors, managing properties with val and var, and implementing custom getters and setters. Understand how Kotlin reduces verbosity compared to Java while enabling immutability and property validation in your code.
We'll cover the following...
Although Kotlin is a multi-paradigm language, it has a strong affinity to the Java programming language, which is based on classes. Keeping Java and JVM interoperability in mind, it’s no wonder that Kotlin also has the notion of classes.
A class is a collection of data, called properties, and methods. To declare a class, we use the class keyword, exactly like Java.
Let’s imagine we’re building a video game. We can define a class to represent the player as follows:
class Player {
}
The instantiation of a class simply looks like this:
val player = Player()
Notice that there’s no new keyword in Kotlin. The Kotlin compiler knows that we want to create a new instance of that class by the round brackets after the class name.
If the class has no body, as in this simple example, we can omit the curly braces:
class Player // Totally fine
Primary constructor
It would be useful for the player to be able to specify their name during creation. In order to do that, let’s add a primary constructor to our class:
class ...