Advanced Kotlin Class Features

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

Lesson 02: Write Extensions

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, 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:

  1. This function is an extension of the FruitBox class.

  2. It calculates the total cost of items in the FruitBox by multiplying the number of items, numOfItems, by the total cost per item, totalCost. The result returns as a Double.

  3. Since numOfItems and totalCost are of type Number, you must convert them to Double before performing arithmetic operations using the toDouble() 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:

  1. val indicates that calTotalCost is a read-only property. Once it’s calculated, its value can’t be changed.

  2. FruitBox<A, B, C, D>.calTotalCost defines that calTotalCost is an extension property of the FruitBox class. It’s declared outside the class and added to instances of FruitBox during runtime.

  3. get() = numOfItems.toDouble() * totalCost.toDouble() is the getter logic for the extension property. It calculates the total cost of the items in the FruitBox instance by multiplying the numOfItems with the totalCost. The result returns as a Double.

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:

  1. In the main function, you create an instance of FruitBox named appleBananaBox with the following values:
  • firstItem: Apple

  • secondItem: Banana

  • numOfItems: 5

  • totalCost: 10.5

  1. The calculateTotalCost function and calTotalCost property are then invoked on appleBananaBox to calculate the total cost of the items in the box.

  2. Finally, the result prints using println to display the total cost of the box and the items inside the FruitBox.

Run the code to see the output to the console.

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