Primary constructor

The best approach is to use a constructor that accepts initial values at the time of object-creation. This constructor is called a primary constructor of a class. The following class declaration is an example of a primary constructor that has three properties. This single line not only declares the class, it also declares the primary constructor of the class:

class Person (val name: String, var age: Int, var height : Double)

We can write primary constructors using the constructor keyword, as shown here:

class Person constructor(val name: String, var age: Int, var height : Double)

This is not mandatory, however; constructors can be declared without the constructor keyword as well.

Each class variable must be declared with either the var or val keyword. Variables without val or var will be considered a normal variable, not a property of the class.

Let's have a look at a complete example:

class Person constructor(val name: String, var age: Int, var height : Double)

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

val p2 = Person("Igor", 35, 6.0)
println("Name ${p2.name}, Age ${p2.age} Height ${p2.height}")
}

By using a primary constructor, each object is assigned different values and each object has its own unique identity:

As you may notice, the class declaration with the primary constructor is more convenient than the default constructor. A single line not only declares the class, but also the class properties. When creating the instance of the class, it is necessary to provide the initial value to each class property:

val p1 = Person("Abid", 40, 6.0)
val p2 = Person("Igor", 35, 6.0)

Class properties can be declared inside the class body and can be initialized using constructor parameters. This approach is the combination of the previous two approaches. We can declare the name, age, and height properties within the class body and initialize them using the pName, pAge, and pHeight constructor parameters:

class Person (pName: String, pAge: Int, pHeight: Double) {
val name: String = pName
var age: Int = pAge
var height : Double = pHeight
}

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

Here, we have created an object of the Person class and passed the required values to the constructor parameters. These parameters assign their values to the class properties. Using a primary constructor is a good way to initialize properties, but Kotlin provides an even better method to do this.

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

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