Reputation: 6220
I am a little bit confused using companion objects in scala. When you want to provide multiple constructors, usually you declare a companion object and overload the apply
method. But what is the difference between this two ways of doing it?:
case class Node(....)
object Node {
def apply(...) = new Node(....) // 1 way
def apply(...) = Node(...) // second way
}
Almost all examples I've seen use the first form:
But my code seems to work the same using both forms. Does using new
keyword only have sense when we have a normal class? (Not a case class)?
Upvotes: 2
Views: 287
Reputation: 149538
When you call
val n = Node(..)
The compiler will expand the code to a Node.apply
call. Now, one of these apply
methods will internally have to call new
in order to create an instance of the type. Case classes provide companion objects with an apply
method for you out of the box to allow the shorter syntax.
When you want to provide multiple constructors, usually you declare a companion object and overload the apply method
This is the case for case classes. You can also provide additional auxiliary constructors using this()
:
class Foo(i: Int) {
def this() {
this(0)
}
}
Note this will not provide the syntax sugar apply
does, you'll need to use new
.
Upvotes: 2
Reputation: 14825
When you declare a case class. A companion object is generated by the compiler with apply method in it whose implementation creates the object of the case class using new keyword.
So you need not create a companion object again with apply method creating object of the case class using new keyword. This work will be done by the compiler
Upvotes: 1