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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use the
newkeyword when you want to refer to aclass‘s own constructor:Omit
newif you are referring to the companion object’sapplymethod: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
applymethod has to be a proxy for the constructor:
And, since you mentioned Java classes: yes — Java classes rarely have
companion objects with an
applymethod, so you must usenewand the actualclass’s constructor.