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

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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.

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()
}
companion object {
  const val BOX_CAPACITY = 10
  fun getDefaultBox(): FruitBox<String, String, Int, Double> {
    return FruitBox("Apple", "Banana", 8, 14.2)
  }
}
println("\nCalling Companion Object")
println("Box Capacity: ${FruitBox.BOX_CAPACITY}")

val defaultBox = FruitBox.getDefaultBox()
defaultBox.printContents()
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion