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

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 : Number, D : Number>(
  val firstItem: A,
  val secondItem: B,
  val numOfItems: C,
  val totalCost: D
)

fun main() {
}
fun <A, B, C : Number, D : Number> FruitBox<A, B, C, D>.calculateTotalCost(): Double {
  return this.numOfItems.toDouble() * this.totalCost.toDouble()
}
val <A, B, C : Number, D : Number> FruitBox<A, B, C, D>.calTotalCost: Double
    get() = numOfItems.toDouble() * totalCost.toDouble()
val appleBananaBox = FruitBox("Apple", "Banana", 5, 10.5)
println("Extension Function - Total Cost: $${appleBananaBox.calculateTotalCost()}")
println("Extension Properties - Total Cost: $${appleBananaBox.calTotalCost}")

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