just a question…
I read that Kotlin is created with Effective Java in mind.
Effective Java tells that utility-functions should be put in a class with a private constructor which throws an Assertion-error.
If I’m right, this matches the top-level-functions.
Is there a specific reason why those don’t have a private constructor in Java?
just a question…
What is “those” refering to?
sorry, my bad.
You mean why the generated jvm class, that contains these toplevel functions, doesn’t have a private constructor? This is a good question and I have no answer, but adding it now would break code that already creates (useless) instances of the class.
yep, that was what I meant.
I was just curious, as the language was written with this book in mind.
This means they either didn’t think about the top-level functions as related to this item, or they made an explicit choice not to do this.
When it’s the first, maybe a deprecated constructor could be added?
It’s not as clear as removing it entirely, but it warns when extending the class…
But this is just a theoretical question as I was just comparing Kotlin with this book.
This Effective Java item is about making the intent of a class and it’s intended usage clear.
This goal is already achieved in pure Kotlin code, as you cannot create instances of that class from pure Kotlin code. Or can you?
In Java code, a Kotlin top level function cannot be used as they are intended to be used anyway. Even if the constructor were private. So it doesn’t matter.
Ah, of course.
That was the part I was missing.
For a long time I did not see the point of preventing instantiation of a utility. If someone wants to waste their time doing so, why do I care? It isn’t as though that gives them any special power to get around any safeguards unless you declared something as protected.
The only actual valid reason for not having a constructor is that it pollutes the code completion namespace with types that never need to be instantiated.
Actually in Java a private constructor, it also stops people from thinking it can/should be instantiated (as otherwise a default empty constructor is created). Remember that in Java you can validly call static methods upon an instance although most decent compilers generate warnings if you do so.
But my point was there is no actual reason that needs to be prevented. It isn’t like there is a security loophole that they can bypass because of being able to instantiate the class (unless you did something silly like declaring static things protected).
But like I said keeping it from showing up in code completion is reason enough.