Can someone explain me difference between a constructor and apply() method?

Newbie to Scala
Googled the same still could not get it😅

The distinction is covered in this article I wrote specifically about case classes. However, the constructor and apply information in the article are the same for (non-case) classes.

2 Likes

In comparison to Java, the Scala:

  • apply(...) method on companion object can be considered a factory method. Implementation details: in Scala companion objects can inherit from superclasses too and Scala then generates static method forwarders. You can even override the inherited methods in companion object. That’s not possible with typical static methods in Java.
  • constructor is mostly the same thing. However syntax is a bit different. There’s main constructor that you write after class name and there are secondary constructors that you define with def this(...) { ... } inside the class (not companion object). This is somewhat similar to Java records.

For case classes Scala generates hashCode, toString, equals, unapply, etc based on the main constructor, so you want to keep in the main constructor exactly the fields that you want to have in that methods.

It’s best to avoid any side effects in a constructor: Flaw: Constructor does Real Work Additionally, constructor doesn’t let you return e.g. IO monad, so side effects needed to construct the object need to be executed imperatively (if you want to put them in constructor). If side effects are needed to construct an object then use apply() method. If you use IO monad then that apply() method can return IO[YourClass].

something.apply(...) can be shortened to something(...) in both Scala 2 and Scala 3, while new Something(...) can be shortened to Something(...) only in Scala 3. Therefore writing apply() reduces noise at call site in Scala 2 (which is still a majority among Scala projects).

2 Likes

https://alvinalexander.com/scala/how-to-create-factory-method-in-scala-apply-object-trait/
https://docs.scala-lang.org/scala3/reference/other-new-features/creator-applications.html#

1 Like

Don’t Google things, learn from proper sources (especially if you are a newbie).
Here is the book by the language creator and it explains apply methods early in the book in Chapters 3 and 4:

It also explains what has been said above (how constructors are often rewritten by the compiler as the apply factory methods from the companion object):

2 Likes

:sunglasses:

1 Like