Removing Constructor Keyword

I am learning kotlin and when I don’t understand many things, first I Google! However, even after that if I don’t understand, I post my concern here! I hope, I am not disturbing anyone!

So, I was reading about the constructor keyword in kotlin and there is one confusion.

According to document:

If the primary constructor does not have any annotations or visibility modifiers, the constructor keyword can be omitted

Does that mean we cannot remove constructor keyword if our properties have any kind of annotation or even when our properties have visibility modifier?

What I have observed is quite different than what document says! We can remove the constructor keyword even if the properties have any visibility modifiers!

Have I got this wrong?

No, this line only is about visibility modifiers and annotations on the primary constructor.

class Foo internal constructor() // can't remove the constructor keyword here
class Bar constructor()  // here you can remove the keyword

Same is true for annotations that apply to the primary constructor.

There is an example for this in the docs as well a bit further down. Maybe you just missed it :wink:

If the constructor has annotations or visibility modifiers, the constructor keyword is required, and the modifiers go before it:

class Customer public @Inject constructor(name: String) { /*...*/ }
1 Like