Kotlin Notes - 1

发布时间 2023-11-13 15:16:46作者: Otlpy

A class in Kotlin has a primary constructor and possibly one or more secondary constructors.

  // primary constructor
  class Person(val name: String) {
    val children: MutableList<Person> = mutableListOf()
    // secondary constructor
    constructor(name: String, parent: Person) : this(name) {
        parent.children.add(this)
    }
}

Code in initializer blocks effectively becomes part of the primary constructor. So the code in all initializer blocks and property initializers is executed before the body of the secondary constructor.

  class Constructors {
    init {
        println("Init block")
    }

    constructor(i: Int) {
        println("Constructor $i")
    }
}

To create an instance of a class, call the constructor as if it were a regular function:

  val invoice = Invoice()

  val customer = Customer("Joe Smith")

All classes Kotlin have a common superclass: Any, like Object in Java. Any has three methods: equals(), hashCode(), and toString().

By default, Kotlin classes are final. To make a class inheritable, mark it with the open keyword:

  open class Base // Class is open for inheritance

To declare an explicit supertype, place the type after a colon in the class header:

  open class Base(p: Int)

  class Derived(p: Int) : Base(p)

Kotlin requires explicit modifiers for overridable members and overrides:

  open class Shape {
    open fun draw() { /*...*/ }
    fun fill() { /*...*/ }
  }

  class Circle() : Shape() {
      override fun draw() { /*...*/ }
  }

Overriding properties:

  open class Shape {
    open val vertexCount: Int = 0
  }

  class Rectangle : Shape() {
      override val vertexCount = 4
  }
  
  // Note that you can use the override keyword as part of the property declaration in a primary constructor:
  class Rectangle(override val vertexCount = 4) : Shape {}

Base class initializes before derived class

  open class Base(val name: String) {

    init { println("Initializing a base class") }

    open val size: Int = 
        name.length.also { println("Initializing size in the base class: $it") }
  }

  class Derived(
      name: String,
      val lastName: String,
  ) : Base(name.replaceFirstChar { it.uppercase() }.also { println("Argument for the base class: $it") }) {

      init { println("Initializing a derived class") }

      override val size: Int =
          (super.size + lastName.length).also { println("Initializing size in the derived class: $it") }
  }