Tuesday, April 21, 2009

Optional arguments in Scala

I couldn't find much on the web with this search and it took me maybe 15 min to figure it out, so here's the low down on using optional arguments in Scala. There's a description in section 8.8 in the Programming in Scala book - they call them "repeated parameters".

Using this notation you can overload Java methods with optional parms as well as pass them over to a "super." method (which was what I needed to do):

def takesOptionalArgs (x:String*) = {
println ("Scala println: ", x.mkString(" "))
java.lang.System.out.printf ("Java printf: %s %s %s", x:_*)

This special syntax instructs the compiler to pass the x array elements individually, not as an array!


[later edit] P.S. Note that there's an outstanding defect for overloading java vararg methods - it currently doesn't work: https://lampsvn.epfl.ch/trac/scala/ticket/1459
blog comments powered by Disqus