Kotlin Class: Calculate the total cost of a product
Kotlin Class: Exercise-10 with Solution
Write a Kotlin program that creates a class 'Product' with properties for name, price, and quantity. Calculate the total cost of the product with a function.
Sample Solution:
Kotlin Code:
class Product(
val name: String,
val price: Double,
val quantity: Int
) {
fun calculateTotalCost(): Double {
return price * quantity
}
}
fun main() {
val product = Product("Desktop", 2000.0, 4)
val totalCost = product.calculateTotalCost()
println("Total Cost: $totalCost")
}
Sample Output:
Total Cost: 8000.0
Explanation:
In the above exercise -
- In this program, we define a class "Product" with three properties: name, price, and quantity, representing the product's name, price, and quantity.
- The class includes a function "calculateTotalCost()" that calculates the total cost of the product by multiplying the price by the quantity.
- In the "main()" function, we create an instance of the Product class named product with the name "Desktop", a price of 2000.0, and a quantity of 4. We then call the calculateTotalCost function on the product object and store the result in the totalCost variable.
- The println function is used to print the total cost calculated.
Kotlin Editor:
Previous: Triangle class with perimeter calculation.
Next: Create an Animal class and make animal sounds.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/kotlin-exercises/class/kotlin-class-exercise-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics