Classes in Kotlin

Classes in Kotlin are created using the class keyword, which is depicted as follows:

class User {

}

The structure of the class is as follows:

Class className {
//properties and constructor
//member functions
}

Let's write a class for User.

Consider the following code for 14_Class.kts:

class User {
var name = "George"
}

val user = User()
println(user.name)

The output is as follows:

This class has a property called name. Classes are instantiated with just the class name, followed by parentheses. Note that there is no new keyword in Kotlin to create an object, unlike in Java.

Classes in Kotlin are final by default. We cannot extend from a class directly. To inherit from the classes, we have to open the classes explicitly. Classes need to have an open keyword in their declaration, as shown in the following code:

open class Person {

}

Alternatively, we can use all-open compiler plugins to make all the classes extendable or accessible to frameworks such as JPA and Spring. We will discuss compiler plugins further in the next chapter.

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

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