Constructing the Basics: Kotlin Constructors and Initialization Explained
Understanding Primary Constructors
In Kotlin, a constructor is a special function for creating an instance of a class. The primary constructor is an integral part of the class declaration. It initializes the class with parameters passed to it when an object is created. Here's the full syntax for defining a class with a primary constructor and manually initializing its properties:
In this detailed syntax, we define each property inside the class body and initialize them with the constructor parameters. The use of val for brand and model makes them immutable (read-only), while var for color allows it to be mutable.
Simplifying Property Declaration in Constructors
Kotlin allows for a more concise syntax to declare and initialize properties directly in the primary constructor. This shorthand notation automatically defines the properties with the constructor parameters, eliminating the need for manual property initialization:
This version clearly shows how Kotlin's concise constructor syntax can define and initialize both mutable (var) and immutable (val) properties directly. This approach significantly reduces boilerplate, making your code more readable. Properties declared as val are immutable, meaning once assigned, their values cannot be changed, while var properties are mutable and can be modified.
