quantity (Int): The initial quantity of the product.
Implement a custom setter for the quantity property that ensures that negative values are set to zero.
Add a method named calculateTotalValue that returns the product's total value.
Implement a method named restock that increases the product's quantity by a specified positive amount. If a negative value is specified, the method should do nothing.
Instructions:
Define the Product class with primary constructor properties name, price, and parameter quantity.
Implement a property quantity with a custom setter.
Implement the calculateTotalValue method to calculate and return the total value.
Implement the restock method to increase the quantity.
Test your implementation by creating instances of the Product class and using its methods.
This problem can either be solved in the below playground or you can clone kotlin-exercises project and solve it locally. In the project, you can find code template for this exercise in essentials/classes/Product.kt. You can find there example usage and unit tests.
Hints:
Use the field keyword in the custom setter to modify the backing field.
Calculate the total value by multiplying price and quantity.
Once you are done with the exercise, you can check your solution here.
Marcin Moskala is a highly experienced developer and Kotlin instructor as the founder of Kt. Academy, an official JetBrains partner specializing in Kotlin training, Google Developers Expert, known for his significant contributions to the Kotlin community. Moskala is the author of several widely recognized books, including "Effective Kotlin," "Kotlin Coroutines," "Functional Kotlin," "Advanced Kotlin," "Kotlin Essentials," and "Android Development with Kotlin."
Beyond his literary achievements, Moskala is the author of the largest Medium publication dedicated to Kotlin. As a respected speaker, he has been invited to share his insights at numerous programming conferences, including events such as Droidcon and the prestigious Kotlin Conf, the premier conference dedicated to the Kotlin programming language.