I have a very simple question - when should we apply the new keyword when creating objects in Scala? Is it when we try to instantiate Java objects only?
相关问题
- Unusual use of the new keyword
- Get Runtime Type picked by implicit evidence
- What's the point of nonfinal singleton objects
- PlayFramework: how to transform each element of a
- Error in Scala Compiler: java.lang.AssertionError:
相关文章
- es 单字段多分词器时,textField.keyword无法高亮
- Gatling拓展插件开发,check(bodyString.saveAs("key"))怎么实现
- RDF libraries for Scala [closed]
- Why is my Dispatching on Actors scaled down in Akk
- How do you run cucumber with Scala 2.11 and sbt 0.
- GRPC: make high-throughput client in Java/Scala
- Setting up multiple test folders in a SBT project
- Testing request with CSRF Token in Play framework
Use the
new
keyword when you want to refer to aclass
's own constructor:Omit
new
if you are referring to the companion object'sapply
method:If you've made a case class:
Scala secretly creates a companion object for you, turning it into this:
So you can do
Lastly, keep in mind that there's no rule that says that the companion
apply
method has to be a proxy for the constructor:And, since you mentioned Java classes: yes -- Java classes rarely have companion objects with an
apply
method, so you must usenew
and the actual class's constructor.Not at all. There is two general cases when you ommit
new
in scala. With singleton objects (that are oftenly used to store static functions and as a kind of factory similar to what you may seen in java):With a case classes (actually, underneath there are class + object = companion pattern, e.g. having class and object with the same name):
So when you work with a simple classes, rules are the same as with Java.
Bonus, there is a anonymous classes in scala, which can be constructed like this: