简体   繁体   中英

What does apply function do in Scala?

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)

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.

Eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM