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. 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, D>(
val firstItem: A,
val secondItem: B,
val numOfItems: C,
val totalCost: D
) {
fun printContents() {
println("FruitBox contents: First Item = $firstItem, Second Item = $secondItem")
println("Total Items = $numOfItems, Total Cost = $$totalCost")
}
}
fun main() {
val appleBananaBox = FruitBox("Apple", "Banana", 5, 10.5)
appleBananaBox.printContents()
}
Now, you’ll create a companion object block within the FruitBox class with the following members:
companion object {
const val BOX_CAPACITY = 10
fun getDefaultBox(): FruitBox<String, String, Int, Double> {
return FruitBox("Apple", "Banana", 8, 14.2)
}
}
Here’s a code breakdown:
-
const val BOX_CAPACITY = 10defines a constant property,BOX_CAPACITY, representing the maximum capacity of the fruit box. -
fun getDefaultBox()is a function that returns a defaultFruitBoxinstance initialized with predefined values:"Apple","Banana",8, and14.2.
Next, you need to update the main() function to display the results of the companion object members in the console. Update the main() function with the following code:
println("\nCalling Companion Object")
println("Box Capacity: ${FruitBox.BOX_CAPACITY}")
val defaultBox = FruitBox.getDefaultBox()
defaultBox.printContents()
Here’s a code breakdown:
-
println("\nCalling Companion Object"): Prints a message indicating that the companion object is being called. -
println("Box Capacity: ${FruitBox.BOX_CAPACITY}")prints the box capacity by accessing the constant propertyBOX_CAPACITYfrom theFruitBoxclass using its companion object. -
val defaultBox = FruitBox.getDefaultBox()calls thegetDefaultBox()function from the companion object ofFruitBoxto create a default box instance. -
defaultBox.printContents()calls theprintContents()function on thedefaultBoxinstance to print its contents.
Run the code to see the output to the console.