Use Kotlin Classes

May 22 2024 · Kotlin 1.9.24, Android 14, Kotlin Playground

Lesson 02: Use Properties

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

In the lesson, you learned about Delegated properties. Now, look into one of the cases when these properties are valuable.

class Rectangle(val length: Double, val width: Double) {
  val area: Double
    get() = (length * width).also { println("Calculating area") }

  val perimeter: Double 
    get() = 2 * (length + width).also { println("Calculating perimeter") }
}
fun main() {
  val rectangle = Rectangle(5.0, 3.0)
  println("Area: ${rectangle.area}") 
  // Calculating area
  // Area: 15.0
  println("Area: ${rectangle.area}")
  // Calculating area
  // Area: 15.0
  println("Perimeter: ${rectangle.perimeter}") 
  // Calculating perimeter
  // Perimeter: 16.0
  println("Perimeter: ${rectangle.perimeter}")
  // Calculating perimeter
  //  Perimeter: 16.0
}
  val area: Double by lazy {
    (length * width)
      .also { 
        println("Calculating area") 
      }
  }

Calculating area
Area: 15.0
Area: 15.0
Calculating perimeter
Perimeter: 16.0
Calculating perimeter
Perimeter: 16.0
Calculating area
Area: 15.0
Area: 15.0
Calculating perimeter
Perimeter: 16.0
Perimeter: 16.0
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion