And now for something entirely 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 didnot google well. Here goes...

In Scala, you declare varargs like this:

def sum(args: Int*) = {
  var result = 0
  for (arg <-args.elements) result += arg

Think of Int* as a sequence of 0 or more integers. In Java, an int... is transformed into anint[], and in Scala, an Int* becomes aSeq[Int].

Of course, you can call



But you can't call

sum(1 to 5)

What gives? 1 to 5 is a Range[Int], and that's a subtype of Seq[Int]. But unlike Java, Scala insists that you pass a sequence of Int tosum, not a Seq[Int].

The remedy, as explained in the Scala Reference Section 4.6.2, is to call

sum(1 to 5 : _*)

that is, 1 to 5 as a sequence of something.

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 : _*cast:

def sum(args: Int*) : Int = 
  if (args.length == 0) 
    0 else 
    args.head + sum(args.tail : _*)