Wednesday, April 20, 2016

Scala varargs and splats

Coming from a Python background, I got a lot of mileage out of the easy sequence parameter expansion pattern:

def foo(a,b,c): bar()
L = [1,4,"s"]
foo(*L)

This implicitly takes a sequence type (in this case, a list) and explodes its contents into the parameters a,b,c. (You have to watch out that the sequence  contains the right number of parameters, of course.)

In Scala, which I'm writing for my current job, I was pleasantly surprised to find that the same kind of functionality exists, as long as the function is declared varargs:

def foo(ts: T*)
L = List(t0,t1,t2)
foo(L :_*)

This is especially useful if, for example, foo() is defined in some Java library that doesn't do any kind of polymorphism well.

Apparently, the ":_*" type annotation on the end there is called the "splat operator" (much easier to pronounce), and it's a part of the Scala Language Specification.

No comments:

Post a Comment