Use Kotlin Classes

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

Lesson 03: Construct Class Instances

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

How do you know when to use a primary constructor and when a secondary constructor is a better option? For example, you can have default values in the primary constructor and not use the ones you don’t really need.

class Measurements(val length: Int, val width: Int, val depth: Int = 0)
class Measurements2(val length: Int, val width: Int, val depth: Int) {
  constructor(length: Int, width: Int) : this(length, width, 0)
}
class User(val name: String, age: Int = 18)
class Address(val street: String, val city: String) {
  constructor(postalCode: Int) : this(extractStreet(postalCode), extractCity(postalCode)) {
    println("using $street and $city values extracted from $postalCode")
  }

  companion object {
    private fun extractStreet(postalCode: Int): String {
      println("implementation to extract street from postalCode")
      return "street in $postalCode"
    }

    private fun extractCity(postalCode: Int): String {
      println("implementation to extract city from postalCode")
      return "city in $postalCode"
    }
  }
}

fun main() {
  val address = Address(12345)
//implementation to extract street from postalCode
//implementation to extract city from postalCode
//using street in 12345 and city in 12345 values extracted from 12345
}
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion