Exercise: Implementing the Product Class

Enhance your Kotlin skills by creating and handling product information with custom setters and methods.

We'll cover the following

Problem statement

Your task is to include the necessary properties and functionalities according to the instructions below:

  1. Implement the Product class with the following properties:

    1. name (String): Representing the product’s name

    2. price (Double): Indicating the product’s price

    3. quantity (Int): Denoting the initial quantity of the product

  2. Create a custom setter for the quantity property, ensuring that negative values are automatically set to zero.

  3. Introduce a method called calculateTotalValue within the Product class to compute and return the total value of the product. The total value is defined as the product of quantity and price.

    1. Example: If the product quantity is 3, and the price is 100, the function should return 300.

  4. Implement a method named restock in the Product class, allowing an increase in the product’s quantity by a specified positive amount. The method should take the restock quantity as an argument. If a negative value is specified, the method should have no effect.

Tips:

  • Use the field keyword in the custom setter to modify the backing field.

  • Calculate the total value by multiplying price and quantity.

Instructions

In the provided code, you are provided with the initial structure of a Product class designed to represent a retail product. Your task is to complete the functionality of this class by following the above instructions:

The actual output when running the provided code should be as follows:

Get hands-on with 1200+ tech skills courses.