1

I know we cant get that effect by defining by ourselves an apply() method on the companion object, but for all purposes the only thing I end up seeing in Scala code-bases is that everyone will just define apply() methods for each of their classes, thus leading to a lot of boilerplate code.

F#, for instance, will allow the instantiation of objects without new by default (other than for disposables).

Is there any reason for this decision?

devoured elysium
  • 101,373
  • 131
  • 340
  • 557
  • 1
    You can instantiate an instance of a case class without use of new. http://docs.scala-lang.org/tutorials/tour/case-classes.html – Simon Dec 14 '15 at 09:39
  • With case classes, the companion object and the `apply` method is generated automatically for you, so you don't have to write it yourself. – Jesper Dec 14 '15 at 09:57
  • You probably won't get an answer, as this might have been a decision simply for being similar to Java. Personally, I would have preferred that the `new` keyword didn't exists and you would simply write `Foo()` or `Foo.new()`. Perhaps this was dealt with in the Scala-Virtualized project. Also see: https://programmers.stackexchange.com/questions/47678/why-did-memory-managed-languages-like-java-javascript-and-c-retain-the-new – 0__ Dec 14 '15 at 10:42
  • I believe this is a hangover from java (and I can't find any evidence this was a concious decision). Like others have said, case classes do this automatically - there is a good comparison between the two here: http://stackoverflow.com/questions/2312881/what-is-the-difference-between-scalas-case-class-and-class – Hamish Dec 14 '15 at 10:46

1 Answers1

6

This has been discussed a while back on the scala-language mailing list.

Martin Odersky points out:

One problem with leaving out new is that ambiguities arise for anonymous classes: Instead of

new Foo(x) { def y = x + x }

you'd get:

Foo(x) { def y = x + x }

The parser would reject this, because it thinks that the braces { ... } enclose a function argument, so definitions would not be allowed.

I would also add that you'll have problems with parameter-less constructors. Like

class Foo

How would you instantiate this, especially if there was a companion object? Of course, one could have kept new for these cases as an optional keyword.

A more theoretical reflection is that in class Foo, Foo is a type not a value. In general, you cannot call any methods on a type, such as synthetic apply() or a hypothetical .new(). For case classes apply is defined on the companion object which is a value. Then adding a synthetic apply to any class would imply that you always get a (synthetic) companion object for any class.

It would not have been impossible to do away with the new. In the experimental Scala-Virtualized project you do have a virtual new. For the same aesthetic question one could have done away with if and while etc.

0__
  • 66,707
  • 21
  • 171
  • 266