Sobes.tech
Junior

Kuidas rakendada Kotlinis ühes klassis mitut konstruktorit?

sobes.tech AI

Vastus AI-lt

In Kotlin, a class can have one primary constructor and one or more secondary constructors.

  1. Primary constructor: Defined in the class header. It can have parameters.

    class MinuKlass(private val mingiOmadus: String) { // Primary constructor with parameter
        // Class body
    }
    
  2. Secondary constructors: Declared with the keyword constructor. If the class has a primary constructor, each secondary constructor must delegate directly or indirectly to it using this().

    class TeineKlass(private val peamineVäärtus: Int) { // Primary constructor
    
        constructor teineVäärtus: String) : this(teineVäärtus.length) { // Secondary constructor delegating to primary
            // Secondary constructor logic
            println("Loodud stringiga: $teineVäärtus")
        }
    
        constructor(väärtus1: Int, väärtus2: Int) : this(väärtus1 + väärtus2) { // Another secondary
            // Logic
            println("Loodud kahe intiga: $väärtus1, $väärtus2")
        }
    }
    

If there is no primary constructor, secondary constructors are not required to delegate to other constructors of the same class (but can).

class IlmaPrimaarse {

    constructor(väärtus: Int) {
        println("Loodud intiga: $väärtus")
    }

    constructor(väärtus: String) {
        println("Loodud stringiga: $väärtus")
    }
}