The primary constructor does not contain any code other than the properties and their specified data types. What if we’d like to calculate a person’s age using the year they were born? We can do this with an init block.

Init is short for initializer and allows us to add more logic to our classes.

Suppose the following class, Mascot:

class Mascot(val name: String, val platform: String, val yearCreated: Int)

We’d like to use the year the mascot was created to calculate its age. We can do so by adding this logic within an init block:

class Mascot(val name: String, val platform: String, val yearCreated: Int) { var age: Int init { age = 2020 - yearCreated println("$name is a $platform mascot and is $age years old. ") } }
  • We’ve created a variable, age, within the class that we’ll use to store the value of the calculation.
  • Within the init block, we add our mathematical expression followed by a println() statement to output the final result.

Now when we call the class, we should expect to see a String output:

val codey = Mascot("Codey", "Codecademy", 2018) // Prints: Codey is a Codecademy mascot and is 2 years old.



In Employee.kt, we’ve created a class that accepts several properties in its primary constructor.

On the first line within the class, declare a variable, fullName and in it store the combination of firstName and lastName with a single space in between.

You can use String concatenation or String templates.


Below, create an init block and in its body, set up the following logic:

  • if the yearsWorked is greater than 1, then output the text, "[full name] is eligible for a raise!"

  • else output the text, "[full name] is not eligible for a raise just yet."

Make sure to use the variable you created in the previous step and String templates.


Navigate to the main() function and create an instance, projectManager, of the class Employee and pass in the following values:

  • firstName is "Maria"
  • lastName is "Gonzalez"
  • yearsWorked is 2

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?