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.
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:
