Class constructors
In Kotlin, class constructors can be defined in two ways, as primary and as secondary constructors.
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...