Primary constructor with the init block

Having code directly in the class body is not a clean approach. Instead, Kotlin provides a very useful init block to initialize the class properties. We will describe the syntax of the init block here.

Create a block with the init keyword and initialize all properties within the block with class parameters:

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

The primary constructor and the init function are linked together. The init function will only be executed when the class is created using a primary constructor:

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

init {
name = pName
age = pAge
height = pHeight
}
}

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

The init function is not only a property initializer, it can also help to validate properties before initialization. In the Person class, for example, it can verify that the provided age and height are not negative and the person's name is not empty. Kotlin's require function can help to achieve this validation. You can mention the minimum requirement in the require function, as follows:

require(age > 0 ) {"Age is not correct"}

The require function verifies whether the provided age is greater than or equal to 0, or whether it is negative:

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

init {
name = pName
age = pAge
height = pHeight

require(name.trim().isNotEmpty()) {"Name should not empty"}
require(age > 0 ) {"Age is not correct"}
require(height > 0) {"Height is not correct"}
}
}

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

Kotlin throws IllegalArgumentException along with a message provided in the require function:

Pass some invalid arguments to the Person class and verify the init function. The following functions can also be used for validation:

  • require
  • requireNotNull
  • check
  • checkNotNull

Before moving to the secondary constructor, it is necessary to discuss an important topic: the this keyword

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

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