Wednesday, April 30, 2014

Variable arguments in Scala

Almost all modern day languages have a facility to create methods/functions which take in variable number of arguments. Some of the languages that had varargs feature almost since circa 1857 include C, C++, Python, PHP, Common Lisp, JavaScript. Quite surprisingly Java did not have this feature for a long time. Java release 5 fixed that with the varargs feature in the form of ellipsis (which seems to be inspired by ellipsis in the C Programming language). Python has this interesting and somewhat mysterious (at least at first glance) *args and **kwargs, Lisps have the & - the keyword argument, PHP has func_num_args() and func_get_args(), Javascript has arguments. Each of these is instructive enough to deserve a post of its own, but that's for some other day. Today is for Scala .

Here is how you could define a Scala function that takes variable number of arguments:
def varArgsDemo(allArgs: String*) = {
        println("*****************Don't know how many args have been passed, but will print whatever you give me")
        for(anArg <- allArgs )


          println("Printing an arg: "+ anArg)         
      }
varArgsDemo: (allArgs: String*)Unit

And here are some calls to the variable argument function we just created -

varArgsDemo(" Scala can be confusing")
varArgsDemo(" Scala can be confusing", " Clojure is cute")
varArgsDemo(" Scala can be confusing", " Clojure is cute", "Python takes the cake")

Output: 
*****************Don't know how many args have been passed, but will print whatever you give me
Printing an arg: Scala can be confusing
*****************Don't know how many args have been passed, but will print whatever you give me
Printing an arg: Scala can be confusing
Printing an arg: Clojure is cute
*****************Don't know how many args have been passed, but will print whatever you give me
Printing an arg: Scala can be confusing
Printing an arg: Clojure is cute

Printing an arg: Python takes the cake

For some reason the variable arguments don’t find enough hype. If you think long enough about them, you will realize that they are a fantastic form of Polymorphism. It’s like method overloading gone wild. But it certainly is the least popular, or shall we say least discussed kind of polymorphism.
-->

No comments:

Post a Comment