Use Kotlin Classes

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

Lesson 06: Implement Interfaces

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

Extending on interfaces, you’ll see that not every conventional rule must be followed. The Kotlin language allows you to build code that makes little logical sense but could help define behaviors.

interface Shape {
  var name: String
    get() = names[this]?.uppercase() ?: "Unknown shape"
    set(value) {
      names[this] = value
    }

  var vertices: Int
    get() = vertexCount[this] ?: -1
    set(value) {
      vertexCount[this] = value
    }

  val details: String
    get() = "The $name has $vertices vertices"

  companion object {
    private val names = mutableMapOf<Shape, String>()
    private val vertexCount = mutableMapOf<Shape, Int>()
  }
}
class Triangle : Shape

class Square : Shape
fun main() {
  val triangle = Triangle()
  triangle.name = "Triangle"
  triangle.vertices = 3

  val square = Square()
  square.name = "Square"
  square.vertices = 5

  println(triangle.details) // The TRIANGLE has 3 vertices
  println(square.details) // The SQUARE has 5 vertices
}
  companion object {
    val names = mutableMapOf<Shape, String>()
  }
  Shape.names.forEach { name ->
    println(name.value)
  }
  // Triangle
  // Square
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion