Scala - New

Updated: 2018-11-30

For new scala programmers, it might be confusion when to use keyword new to create an object. Sometime we see

val foo = new Foo()

while sometime this would work:

val foo = Foo()

Here's the secret.

Class

For any class, use new as in other similar languages(e.g. Java) to create a new object:

class Foo { }

val f = new Foo()

Class with apply() Defined in Companion Object

If the class comes with a companion object, and an apply method is defined, calling the class name Foo() is a shorthand for calling Foo.apply()

class Foo { }

object Foo {
  def apply() = new Foo
}

//either
val f1 = Foo()
//or
val f2 = new Foo()

In this case calling the apply() will create and return a new object by calling the constructor.

But it only works if apply() is implemented to return a new object. It can do anything. calling Foo() is simply a shortcut for Foo.apply()

scala> class Foo {}; object Foo { def apply() = println("Hello") }
defined class Foo
defined module Foo

scala> Foo()
Hello

Case Class

Case class will secretly create a companion object for you

case class Foo()

val f = Foo()

Summary

  • Use the new keyword when you want to refer to a class's own constructor
  • Omit new if you are referring to the companion object's apply method