Classes in Kotlin

In Kotlin, a class can be defined with the class keyword. Let's take a look at how to declare a class and how to add attributes to it. In Kotlin, a class can be declared as follows:

class Person 

Compared to other programming languages, creating a class in Kotlin is very easy. All we need to do is open our IDE and create a person class with three attributes—name, age, and height. The name is a variable of the String type, age is a variable of the Integer type, and height is a variable of the Double type:

class Person {
var name: String
var age : Int
var height : Double
}

We have now declared a Person class with three attributes enclosed in brackets. After writing this code, we will notice that compiler has immediately thrown a Property not initialized error, because we haven't decided that how these properties will be initialized. Let's take a look at how to initialize these properties:

class Person {
var name: String = "Abid"
var age : Int = 40
var height : Double = 6.0
}

As we know, Kotlin is very strict when it comes to initializing variables. All properties of the class must be initialized before the object is ready to use. Once the properties are initialized, it's time to create an instance of the class. Creating a class object is similar to creating an instance of a String or Integer variable. The syntax of the object declaration is as follows:

val person = Person()

Use the val or var keywords for a variable and assign a Person object to it. The two small brackets ask Kotlin to instantiate a new object. Once the object is created, all properties can be accessed using the . (dot) operator. 

Let's take a look at a complete example of the Person class, in which all the properties are initialized with the initial values. The main function creates a Person class object and prints all properties on the screen:

class Person {
var name: String = "Abid"
var age : Int = 40
var height : Double = 6.0
}

fun main(args: Array<String>) {
val person = Person()
println("Name ${person.name}, Age ${person.age} Height ${person.height}")
}

When the instance of the class is created, Kotlin creates the properties and the constructor as well.

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

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