Open your internet browser and search for Kotlin Playground. You’ll see different websites. Select the one provided by the Android Developers page. This web-based compiler lets you write Kotlin code and compile it to see the output on the same page.
Open the starter folder from the course material, and you’ll see a Kotlin file with some code to get you started with this lesson. Here’s the code:
class FruitBox<A, B, C : Number, D : Number>(
val firstItem: A,
val secondItem: B,
val numOfItems: C,
val totalCost: D
)
fun main() {
}
Now, you’ll create an extension function called calculateTotalCost which calculates the total cost of the fruits.
fun <A, B, C : Number, D : Number> FruitBox<A, B, C, D>.calculateTotalCost(): Double {
return this.numOfItems.toDouble() * this.totalCost.toDouble()
}
Here’s a code breakdown:
-
This function is an extension of the
FruitBoxclass. -
It calculates the total cost of items in the
FruitBoxby multiplying the number of items,numOfItems, by the total cost per item,totalCost. The result returns as aDouble. -
Since
numOfItemsandtotalCostare of typeNumber, you must convert them toDoublebefore performing arithmetic operations using thetoDouble()function.
Next, you need to create an extension property called calTotalCost. This property performs the same calculation as the calculateTotalCost extension function. This shows you the difference between the extension function and the extension property.
val <A, B, C : Number, D : Number> FruitBox<A, B, C, D>.calTotalCost: Double
get() = numOfItems.toDouble() * totalCost.toDouble()
Here’s a code breakdown:
-
valindicates thatcalTotalCostis a read-only property. Once it’s calculated, its value can’t be changed. -
FruitBox<A, B, C, D>.calTotalCostdefines thatcalTotalCostis an extension property of theFruitBoxclass. It’s declared outside the class and added to instances ofFruitBoxduring runtime. -
get() = numOfItems.toDouble() * totalCost.toDouble()is the getter logic for the extension property. It calculates the total cost of the items in theFruitBoxinstance by multiplying thenumOfItemswith thetotalCost. The result returns as aDouble.
Now, you must update the main() function to display the calculation result in the console. Update the main() with the following code:
val appleBananaBox = FruitBox("Apple", "Banana", 5, 10.5)
println("Extension Function - Total Cost: $${appleBananaBox.calculateTotalCost()}")
println("Extension Properties - Total Cost: $${appleBananaBox.calTotalCost}")
Here’s a code breakdown:
-
In the main function, you create an instance of
FruitBoxnamedappleBananaBoxwith the following values:
-
firstItem: Apple -
secondItem: Banana -
numOfItems: 5 -
totalCost: 10.5
-
The
calculateTotalCostfunction andcalTotalCostproperty are then invoked onappleBananaBoxto calculate the total cost of the items in the box. -
Finally, the result prints using
printlnto display the total cost of the box and the items inside theFruitBox.
Run the code to see the output to the console.