Learn
Classes
The Init Block

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: Int, val yearCreated: String)

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.

Instructions

1.

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.

2.

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.

3.

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
Folder Icon

Take this course for free

Already have an account?