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
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With