Hi, why should I delegate to primary constructor, ...
# getting-started
g
Hi, why should I delegate to primary constructor, even it doesn't have any parameters or init block in this case?
Copy code
class A(){
    constructor(test:String) : this() {
       //
    }
}
b
You could remove the primary constructor, getting rid of the parentheses after
A
. Then you won't need to to delegate to a primary constructor, since there isn't one anymore
g
but if I have an empty constructor, as in this case, why do I need to delegate?
👀 1
h
AFAIK, delegation to the primary constructor is a part of Java interop that requires to call super/this
b
Gotcha! From a design perspective, I imagine it's following Kotlins general preference to be explicit rather than implicit
g
@Ben Woodworth oh. that actually makes sense. thanks!
b
I can also maybe see a situation where changing a zero-argument secondary constructor to be primary with init blocks (or vice-versa) implicitly/accidentally changes what the other constructors initialize. I can't think of an actual example, but I can imagine this helping avoid errors by forcing you to think about how each secondary constructors delegate/share logic when they previously didn't. I would be curious what the actual rationale was though
🙌 1
r
I love that all constructors have to call the primary constructor. In Java you can't do call hierarchy on one constructor and find all the ways and places that the class is constructed. In Kotlin you can, a single call hierarchy on the primary constructor will show you all the construction points.
💯 1
👍 1
c
It's because: • Only the primary constructor can define properties. • We encourage immutability, so properties can only be initialized in a single place, which is the primary constructor. You'll see that the only way your secondary constructor does something useful is if you define some of your properties as
var
or if it has side-effects, which are both against the goals of the language. That's why secondary constructors are nothing more than helpers to call the primary constructor, which is the only source of truth.
❤️ 1
💯 1
j
All this talk about java interop doesn't make sense to me. Java has no concept of a primary constructor