October 2018
Intermediate to advanced
370 pages
9h 15m
English
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 ...
Read now
Unlock full access