Primary Constructor

Looking to customize your instances? You’ve come to the right place! Kotlin classes provide us with something called a primary constructor that allows us to declare properties and initialize them when we instantiate an object.

Let’s see the shorthand syntax:

class Name(val x: String, val y: String)

We’ve now introduced a pair of parentheses in the class header that define properties, x and y. Previously, we would’ve had something like this:

class Name { val x = "some value" val y = "another value" }

Each property would already have its default value set, but with primary constructors, we give our program the ability to set the values when an instance is created.

Refactoring our Car example from the previous exercise to utilize a primary constructor in the header, we get the following line of code:

class Car(val year: Int, val model: String, val color: String)

Neat, right? Let’s see it in action.

val myCar = Car(2011, "Jeep", "Blue") val friendsCar = Car(2015, "Mazda", "Red")

Now we’ve successfully created unique instances of our Car class and customized their values:

println(myCar.year) // Prints: 2011 println(friendsCar.year) // Prints: 2015



In Person.kt, add a class, Person that contains a primary constructor with the following properties:

  • name with the type, String
  • age with the type, Int
  • favoriteColor with the type, String

Within the main() function, create an instance of the Person class called me and set the values for each property that resemble your characteristics.

On the following line, create another instance of the Person class called myFriend and set the values for each property that resemble their characteristics.


Use a String template along with a println() statement for each object and output the following text:

[name] is [age] years old and ___ favorite color is [favoriteColor].

Make sure to replace the ___ with the appropriate pronoun (my, her, his, or their) to match the instance. Check the hint for guidance.

Folder Icon

Take this course for free

Already have an account?