0

I have below "apply" function, what does apply function do? can you please explain for me?

      def apply[K,V](m1:Map[K,V], m2:Map[K,V], merge: (V,V) => V): Map[K,V] = 
           combine(m1,m2,merge)

1 Answers1

0

The apply function in companion objects and classes has a special meaning in that if an object/class is instantiated without specifying the function, it is the one which is run.

E.g.

object DDF { def apply(text :String) = println(s"got $text") }

DDF("text")    // object called like function. function actually called is apply(String) here.

In your example, the apply function merely calls combine. so X(a,b,c) is the same as X.combine(a,b,c).

The technique is how we have achieve multiple constructors on classes too.

Philluminati
  • 2,649
  • 2
  • 25
  • 32
  • Re: your last paragraph, you can have primary and secondary constructors without `apply` methods. Overloading constructors is a feature even in Java, and Scala allows it as well. It's often cleaner to have a factory in a companion object, but that's a matter of style, not a requirement. Scala 3 makes it even easier, by having constructors synthesize `apply` methods in most cases. – Silvio Mayolo Nov 11 '21 at 22:09