0

I have some code that looks like this:

  object Money {
    def apply(dollars: BigInt, cents: BigInt) = new Money(dollars, cents)
  }

  class Money(dollars: BigInt, cents: BigInt) {
    override def toString() = dollars + "." + cents
  }

I'm trying to understand the benefits of the apply function but so far can only think of it as a type of syntactic sugar so that I don't need to use the new operator to construct a Money object. That is, I don't see a lot of benefit in the apply function, as all it's doing for me is turning this:

val money = new Money(2, 50) 

into:

val money = Money(2, 50)

Am I missing something?

jcm
  • 5,499
  • 11
  • 49
  • 78
  • It is like a Factory method, you can change that (for example return a subclass of Money) without changing all the user code. – Gábor Bakos Mar 12 '14 at 14:03

2 Answers2

1

Don't underestimate syntactic sugar. While it may be possible to accomplish most everything by directly calling .apply(), it's the sugar that makes it nice to use and easy to read.

Let's take functions, for example. All functions are objects in Scala. You could define a function the following way:

object add extends Function2[Int, Int, Int] {
  def apply(x: Int, y: Int): Int = x + y
}

val z = add(1, 2) // same as add.apply(1, 2)

This is about the same as what def add(x: Int, y: Int): Int = x + y does. Allowing () to be syntactic sugar for the apply function lets functions be implemented as objects, yet behave naturally like functions when invoked.

As some comments have pointed out, there's also a convention in Scala that apply methods used directly on companion objects are frequently used for factory methods. Rather than instantiating a new Foo(bar) directly, calling Foo.apply(bar) or Foo(bar) may invoke more complex logic that creates an appropriate result for the given input, be that a Foo or some subclass of Foo.

KChaloux
  • 3,918
  • 6
  • 37
  • 52
1

From Wikipedia

In mathematics and computer science, Apply is a function that applies functions to arguments.

In the case of Scala language, apply() is used to connect Object-oriented and functional programming. In Scala, everything is an object, including functions: Generally speaking the "apply" method is a convenient way to ensure that an object can act as a function.

Marco
  • 1,642
  • 3
  • 16
  • 29