Object-oriented programming

Object-oriented programming is a model of programming language that is based on objects that can represent data. Kotlin supports object-oriented programming in the same way that Java does, but even more strictly. This is because Kotlin doesn't have primitive types and static members. Instead, it provides a companion object:

class Bar {
companion object {
const val NAME = "Igor"

fun printName() = println(NAME)
}
}

The companion object is an object that is created once, during class initialization. In Kotlin, we can refer to members of companion object in the same way as static in Java:

fun test() {
Bar.NAME
Bar.printName()
}

However, under the hood, the nested Companion class is created, and we actually use an instance of this class, as follows:

Bar.Companion.printName();

Moreover, Kotlin supports the following concepts, which make the type system stronger:

  • Nullable types
  • Read-only and mutable collections
  • No raw type of collections

The last point means that we can't compile code, as shown in the following screenshot:

This message means that we have to provide a generic to specify a certain type of this collection.

From the object-oriented programming viewpoint, Kotlin supports the same features as Java. These include encapsulation, inheritance, polymorphism, composition, and delegation. It even provides a language-level construction that helps to implement these concepts.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.181.36