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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access