https://kotlinlang.org logo
Title
d

Dalinar

01/23/2019, 9:26 AM
so, let me see if I got constructors straight... 1. if you have a single constructor then
()
after the classname is not required... 2. however if you have secondary constructors then it is now required 3. and now you might also want to make that constructor private
g

gildor

01/23/2019, 9:27 AM
no, it’s incorrect
contructor keyword is optional for primary constructor and requires for secondary
g

gildor

01/23/2019, 9:28 AM
also one case when you need
constructor
keyword for primary, if you want add annotation to primary constructor or add visibility modifier (what you also mentioned in 3)
d

Dalinar

01/23/2019, 9:30 AM
ok wait
what I mean is if I removed
()
from after the classname, and then have secondary constructors then IDE will give me the error supertype initialization is imposssible without a primary constrctor.. so in this case the
()
is required
but then I should make it a
private constructor
to avoid being able to call a no-args constructor?
my thinking is correct?
d

diesieben07

01/23/2019, 9:33 AM
To create a new instance you always need to use
ClassName()
The
()
are never optional.
ClassName
refers to the companion object of the class.
d

Dalinar

01/23/2019, 9:34 AM
no,
()
in the class declaration i mean - not invoking it -
class Abc: Def()
vs
class Abc(): Def()
a

Alowaniak

01/23/2019, 9:35 AM
it doesn't make a lot of sense to have a secondary constructor but effectively no primary constructor though
d

diesieben07

01/23/2019, 9:35 AM
Yes, the shorthand for calling super (
Def()
in your first example) only works with primary constructor.
It does not make any sense otherwise (which constructor should the super call refer to?)
s

Shawn

01/23/2019, 9:35 AM
class Abc()
isn’t invoking a constructor, it’s a redundant set of parens since your constructor is noarg
d

Dalinar

01/23/2019, 9:36 AM
sure it makes sense, I want to prevent incorrect object creation via noargs constructor in my class
otherwise my lateinit fields won't be initalized properly since that code is in the secondary constructors
d

diesieben07

01/23/2019, 9:36 AM
class Abc() : Def()
is short for:
class Abc : Def {
    constructor() : super() {
    }
}
If you don't specify the primary constructor, Kotlin won't magically add one. So:
class Abc : Def {
    // secondary constructors here
}
In that example
Abc
is guaranteed to have one of it's secondary constructors called (since there is no primary one)
d

Dalinar

01/23/2019, 9:40 AM
thanks for the help
h

hho

01/23/2019, 9:40 AM
d

Dico

01/23/2019, 9:41 AM
You are correct that omitting
()
in your class declaration and including a
constructor
in the body removes the implicit no-arg constructor that would otherwise be present .
1