I never understood it from the contrived unmarshalling and verbing nouns ( an AddTwo class has an apply that adds two!) examples.
I understand that it’s syntactic sugar, so (I deduced from context) it must have been designed to make some code more intuitive.
What meaning does a class with an apply function give? What is it used for, and what purposes does it make code better (unmarshalling, verbing nouns etc)?
how does it help when used in a companion object?
Mathematicians have their own little funny ways, so instead of saying “then we call function
fpassing itxas a parameter” as we programmers would say, they talk about “applying functionfto its argumentx“.applyserves the purpose of closing the gap between Object-Oriented and Functional paradigms in Scala. Every function in Scala can be represented as an object. Every function also has an OO type: for instance, a function that takes anIntparameter and returns anIntwill have OO type ofFunction1[Int,Int].Since everything is an object in Scala
fcan now be treated as a reference toFunction1[Int,Int]object. For example, we can calltoStringmethod inherited fromAny, that would have been impossible for a pure function, because functions don’t have methods:Or we could define another
Function1[Int,Int]object by callingcomposemethod onfand chaining two different functions together:Now if we want to actually execute the function, or as mathematician say “apply a function to its arguments” we would call the
applymethod on theFunction1[Int,Int]object:Writing
f.apply(args)every time you want to execute a function represented as an object is the Object-Oriented way, but would add a lot of clutter to the code without adding much additional information and it would be nice to be able to use more standard notation, such asf(args). That’s where Scala compiler steps in and whenever we have a referencefto a function object and writef (args)to apply arguments to the represented function the compiler silently expandsf (args)to the object method callf.apply (args).Every function in Scala can be treated as an object and it works the other way too – every object can be treated as a function, provided it has the
applymethod. Such objects can be used in the function notation:There are many usage cases when we would want to treat an object as a function. The most common scenario is a factory pattern. Instead of adding clutter to the code using a factory method we can
applyobject to a set of arguments to create a new instance of an associated class:So
applymethod is just a handy way of closing the gap between functions and objects in Scala.