Advanced Kotlin Class Features

May 22 2024 · Kotlin 1.9, Android 14, Android Studio Hedgehog

Lesson 03: Use Companion Objects

Demo

Episode complete

Play next episode

Next
Transcript

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:

  1. const val BOX_CAPACITY = 10 defines a constant property, BOX_CAPACITY, representing the maximum capacity of the fruit box.
  2. fun getDefaultBox() is a function that returns a default FruitBox instance initialized with predefined values: "Apple", "Banana", 8, and 14.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:

  1. println("\nCalling Companion Object"): Prints a message indicating that the companion object is being called.
  2. println("Box Capacity: ${FruitBox.BOX_CAPACITY}") prints the box capacity by accessing the constant property BOX_CAPACITY from the FruitBox class using its companion object.
  3. val defaultBox = FruitBox.getDefaultBox() calls the getDefaultBox() function from the companion object of FruitBox to create a default box instance.
  4. defaultBox.printContents() calls the printContents() function on the defaultBox instance to print its contents.

Run the code to see the output to the console.

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion