Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is constructor() primary constructor in Kotlin?

Tags:

android

kotlin

These is a primary constructor Code A, right ?

Is constructor() a primary constructor in Code B ?

Is there no a primary constructor in Code B ?

Code A

class Person constructor(firstName: String) {
}

Code B

class Person {
    var name: String = ""

    constructor()  // Is this a primary constructor

    constructor(name:String):this(){
        this.name = name
    }

}

Code C

class Person {
    var name: String = ""
    constructor(name:String){
        this.name = name
    }

}
like image 246
HelloCW Avatar asked Sep 07 '25 01:09

HelloCW


2 Answers

In Kotlin, The primary constructor is part of the class header: it goes after the class name (and optional type parameters).

Read more at Classes And Inheritance at official documentation.

So, class B does not have primary constructor defined.

like image 76
Pankaj Kumar Avatar answered Sep 10 '25 05:09

Pankaj Kumar


The primary constructor is the one described in the header, whether it's just marked by the parentheses after the classname or the explicit constructor keyword. What makes the primary constructor special is that its arguments can be used in initializer blocks and property initializers. This is why you have to call the primary constructor from every secondary constructor (if the primary constructor exists) - otherwise you could end up with a half-initialized instance of your class. For example:

class MyClass(x: String) {
    val length = x.length

    constructor() : this("foo") {
        println("secondary constructor used!")
    }
}

If you have a primary constructors, secondary constructors have to eventually call the primary one so that proper initialization can take place. This can happen directly or indirectly, even through multiple steps:

class MyClass(x: String) {
    val length = x.length

    constructor(x: Int) : this(x.toString()) // calls primary ctor
    constructor(x: Long) : this(x.toInt()) // calls previous secondary ctor with Int param
    constructor(x: Double) : this(x.toLong()) // calls previous secondary ctor with Long param
}

And of course two secondary constructors can't call each other:

class MyClass {
    constructor(x: Int) : this(x.toLong()) // Error: There's a cycle in the delegation calls chain
    constructor(x: Long) : this(x.toInt()) // Error: There's a cycle in the delegation calls chain
}

If you don't have a primary constructor at all, your secondary constructors don't have any obligation to call each other. They just have to call the superclass constructor, if there isn't one with no arguments.

like image 35
zsmb13 Avatar answered Sep 10 '25 05:09

zsmb13