Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did kotlin drop the "new" keyword? [closed]

Tags:

kotlin

Why did kotlin drop the new keyword ? It makes it harder to see the difference between a function call and an object allocation.

like image 767
user2922073 Avatar asked Jan 20 '16 01:01

user2922073


People also ask

Why new keyword is not used in Kotlin?

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.

Can we use the new keyword to instantiate a class object in Kotlin?

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.

What is the purpose of the keyword new?

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.

How do I create a new object in Kotlin?

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.


2 Answers

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.

like image 60
miensol Avatar answered Sep 19 '22 12:09

miensol


(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.

like image 35
voddan Avatar answered Sep 18 '22 12:09

voddan