Why did kotlin drop the new keyword ? It makes it harder to see the difference between a function call and an object allocation.
Kotlin does not have a new keyword. To create a class instance, call the constructor just like a regular function. We saw that in the screenshot above. Kotlin has single inheritance from a named superclass, and all Kotlin classes have a default superclass Any , which is not the same as the Java base class java.
Notice that, unlike other object-oriented programming languages like Java, You don't need to use the new keyword to instantiate a class in Kotlin. In fact, new is not a keyword in Kotlin.
The new keyword in JavaScript: The new keyword is used to create an instance of a user-defined object type and a constructor function. It is used to constructs and returns an object of the constructor function.
Before you create objects in Kotlin, you need to define a class. A class is a blueprint for the object. We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc.
The Kotlin Coding Conventions clearly state that:
- use of camelCase for names (and avoid underscore in names)
- types start with upper case
- methods and properties start with lower case
If you follow the above and treat constructor
as regular function that can be called i.e. val invoice = Invoice()
the new
keyword becomes redundant.
Once you accommodate yourself with the convention it's clear what a code is doing.
In fact even in Java code you'll have many implicit allocations that happen just beneath a method call like Collections.singleton(o)
or Guava's Lists.newArrayList()
so I don't think your argument about allocation visibility being better with the new
keyword is fully valid.
(IMO) It was done because there is NO real difference between functions and object construction, i.e. nothing prevents a function to allocate an object (and they often do).
A good example is factory functions. These functions create new objects, but they are in no way class constructors.
AFAIK, the new
keyword was created because of a negative experience with C\C++, where functions, returning new objects, have to be specially marked (by name conventions) in order not to forget to (manually) free the memory. In a auto-memory-managing language like Java\Kotlin it is not a concern.
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