Primary constructors

Kotlin has two ways of declaring a constructor. In the example of the User class, we had a primary constructor. Primary constructors are declared with parentheses after the class name, in the class header.

Specifying the constructor keyword is optional if the constructor doesn't have visibility modifiers or annotations.

Constructors can have parameters, but cannot have any initialization code in them. The Java User class constructor has both parameters and initialization code. Initialization code was needed because the private fields needed to be initialized with values from constructor arguments.

The same code was not needed in Kotlin, because Kotlin allows properties to be declared inside the constructor. When declared like this, they become both properties and constructor parameters. The Kotlin compiler then emits bytecode that resembles the Java user class. It will have fields and a constructor with parameters that initialize the fields. Properties declared inside a constructor can also have visibility modifiers applied to them. We don't have any; they are implicitly public. Here's how you would declare a class with a private constructor-declared property:

class PrivateProperty(private val num: Int)

If you want, you can have only constructor parameters without them being properties. In that case, you have to omit the var or val keyword from the parameter names.

If you need to do some initialization logic, a class body can have an init block in which you can access constructor parameters and do additional object initialization. Let's now write the User class again, with the initializer, and with properties this time declared inside the class body:

class User(firstName: String,
lastName: String,
birthYear: Int) {
var firstName: String
var lastName: String
var birthYear: Int
init {
println("Calling constructor of User class")
this.firstName = firstName
this.lastName = lastName
this.birthYear = birthYear
}
}

This is code is equal to the initial User class we wrote in Kotlin, with one addition that this class prints out to the output each time it is constructed. The init block would otherwise be redundant because we can also initialize the members of a class inline, that is, we can access constructor arguments when initializing the members, as the following example shows:

class User(firstName: String,
lastName: String,
birthYear: Int) {
var firstName: String = firstName
var lastName: String = lastName
var birthYear: Int = birthYear
}

You can have as may init blocks as you want, and they will all be called in the order they were declared, as this example shows:

class MultipleInits {
private var counter = 1

init {
//called first
println("I'm called $counter time(s)")
}

init {
//called second
println("I'm called $counter time(s)")
}
}
..................Content has been hidden....................

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