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?
Use the new
keyword when you want to refer to a class
's own constructor:
class Foo { }
val f = new Foo
Omit new
if you are referring to the companion object's apply
method:
class Foo { }
object Foo {
def apply() = new Foo
}
// Both of these are legal
val f = Foo()
val f2 = new Foo
If you've made a case class:
case class Foo()
Scala secretly creates a companion object for you, turning it into this:
class Foo { }
object Foo {
def apply() = new Foo
}
So you can do
f = Foo()
Lastly, keep in mind that there's no rule that says that the companion apply
method has to be a proxy for the constructor:
class Foo { }
object Foo {
def apply() = 7
}
// These do different things
> println(new Foo)
test@5c79cc94
> println(Foo())
7
And, since you mentioned Java classes: yes -- Java classes rarely have
companion objects with an apply
method, so you must use new
and the actual
class's constructor.