Search code examples
scalacase-classcompanion-object

Using New Keyword inside apply method in a companion object


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)?


Solution

  • 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.