Search code examples
kotlinconstructorclass-constructors

Constructor vs. parameter in Kotlin


What is the difference between:

class Pitch(var width: Int = 3, var height: Int = 5) {

    constructor(capacity: Int): this()

}

and

class Pitch(var width: Int = 3, var height: Int = 5, capacity: Int)

What advantages does the constructor provide?


Solution

  • When you define your class like this:

    class Pitch (var width: Int = 3, var height: Int = 5) {
    
        constructor(capacity: Int): this() {}
    
    }
    

    you can create an instance of Pitch using constructor without parameters, i.e.:

    val p = Pitch()
    
    // also you can invoke constructors like this
    val p1 = Pitch(30)     // invoked secondary constructor
    val p2 = Pitch(30, 20) // invoked primary constructor
    

    When you define your class like this:

    class Pitch (var width: Int = 3, var height: Int = 5, capacity: Int) {
    
    }
    

    all parameters are required except those with default values. So in this case you can't use constructor with empty parameters, you need specify at least one parameter capacity:

    val p = Pitch(capacity = 40)
    

    So in the first case you have an advantage of using constructor without parameters. In the second case if you want to call constructor and pass capacity parameter you should name it explicitly when using constructor.