Introduction
In this chapter, you will be introduced to recipes related to object-oriented programming in Kotlin. Using an OOP approach, you can divide complex problems into smaller problems by creating objects. There are a few differences in Kotlin's style of OOP as compared to Java—for example, in Kotlin, all the classes are closed (final) by default, and if you want them to be extensible, you need to make them open by using an open
keyword. Not only for classes—even the methods are final by default, and you need an open
keyword for them as well. With Kotlin much less code is needed to work with classes and objects. Oh! By the way, did I tell you that we don't even need to use the new keyword while creating the object? So, creating a new object in Kotlin is as simple as this:
var person=Person()
The preceding code will create a mutable object of type Person
, because we have used var
as a modifier. A mutable object means that it can change its value. If you want to create an immutable object...