Why did kotlin drop the “new” keyword? [closed]

2020-07-02 10:48发布

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

标签: kotlin
3条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-07-02 10:57

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.

查看更多
Melony?
3楼-- · 2020-07-02 10:57

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

查看更多
老娘就宠你
4楼-- · 2020-07-02 11:16

Several other languages have no new keyword (Python, Scala, maybe Ceylon) and people who have switched to those languages never seem to miss it. I know I dont.

查看更多
登录 后发表回答