Oct 042011
 

Ruby, Python, and many other dynamic languages have a so-called splat operator that lets you easily invoke a function by providing a list of argument values:

def f(x,y)
  x*y
end

> fArgs = [6,7.0]
=> [6, 7.0]

> f(*fArgs)
=> 42.0

Scala does not have a splat operator per se, but you can achieve the same effect without too much work. Sadly the syntax is different for fixed-arity and variadic functions.

Scala splat for variadic functions

For variadic functions there effectively is a splat operator. If you invoke a variadic function and append :_* to the argument the compiler will perform the splat:

> def g(xs:Int*) = (0 /: xs) (_ + _)
g: (xs: Int*)Int

> val gArgs = List(1,2,3,4)
gArgs: List[Int] = List(1, 2, 3, 4)

> g(gArgs:_*)
res23: Int = 10

Scala splat for fixed-arity functions

> def f(x:Int, y:Double) = x * y
f: (x: Int, y: Double)Double

> val fArgs = (6, 7.0)
fArgs: (Int, Double) = (6,7.0)

> f _ tupled fArgs
res8: Double = 42.0

Magic! The first part, f _, is the syntax for a partially applied function in which none of the arguments have been specified. This works as a mechanism to get a hold of the function object. tupled returns a new function which of arity-1 that takes a single arity-n tuple. It is defined in the Scala Function object,

However, given a List of arguments to pass to f, I’m not sure how to easily convert the List to a Tuple.

p.s. There’s a stackoverflow post about this called “scala tuple unpacking.”

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)