Search |
||
Recursive varargs methods in ScalaPosted by cayhorstmann on October 13, 2009 at 3:36 PM PDT
And now for something entirely different...one of my students asked how to write a recursive function in Scala with varargs. Apparently, the internet has lots of articles complaining about the challenge of calling Java varargs methods from Scala, but this particular issue did not google well. Here goes... In Scala, you declare varargs like this:
def sum(args: Int*) = {
var result = 0
for (arg <-args.elements) result += arg
result
}
Think of
Of course, you can call
But you can't call
What gives? The remedy, as explained in the Scala Reference Section 4.6.2, is to call sum(1 to 5 : _*) that is, My students ran into this when trying to write a recursive function with varargs. The obvious
def sum(args: Int*) : Int =
if (args.length == 0)
0 else
args.head + sum(args.tail)
doesn't work. The trick is again to insert the
def sum(args: Int*) : Int =
if (args.length == 0)
0 else
args.head + sum(args.tail : _*)
»
Related Topics >>
Blogs Comments
Comments are listed in date ascending order (oldest first)
I don't think there is. Int*
Submitted by cayhorstmann on Thu, 2009-10-15 22:15.
I don't think there is. Int* isn't a type, so you can't cast to it. I don't think it is a terrible notation, and coming up with another one would just add more complexity.
|
||
|
Clearer than _*