October 2018
Intermediate to advanced
370 pages
9h 15m
English
In Kotlin, like other programming languages, a class can have more than one constructor. A secondary constructor is prefixed with the constructor keyword and it is created inside the class.
Let's take a look at the following example. The Person class contains a primary constructor with the init block and the secondary constructor with the constructor keyword:
class Person(name: String, age: Int) { var name : String var age : Int var height : Double init { this.name = name this.age = age this.height = 0.0 } constructor(name: String, age: Int, height: Double) : this(name, age) { this.height = height } }
Creating a secondary constructor becomes necessary when you need to initialize a class in different ways. In this example, ...
Read now
Unlock full access