75

Given a function that takes a variable number of arguments, e.g.

def foo(os: String*) =
  println(os.toList)

How can I pass a sequence of arguments to the function? I would like to write:

val args = Seq("hi", "there")
foo(args)

Obviously, this does not work.

David Crawshaw
  • 10,427
  • 6
  • 37
  • 39

1 Answers1

149

foo(args:_*) does the trick. Instead of applying the sequence as one single argument, each element in the sequence will be used as an argument.

Joa Ebert
  • 6,565
  • 7
  • 33
  • 47
  • 9
    is there a code-review friendly, less headache prone name to the above function ```args:_*``` – Richeek Jun 16 '15 at 21:31
  • One way to provide an api that makes this transparent, is write a proxy function same named `foo`, which makes the conversion. That way your original call to `foo` would work without your user code having to worry about that. Having said that, if `foo` required a collection such as a `Seq` rather than a primitive type like `String`, the invariance of scala's collections would hamper any sane usage of your api. As if variable argument lists and the standard library collections have not been designed for mutual use cases beyond vanilla. – matanster Nov 27 '15 at 08:17
  • @Richeek Unfortunately, no. – Malcolm Jul 23 '16 at 03:25
  • 12
    With a little and subtle style change `foo(args: _*)` would hopefully be a little more less cryptic (notice the added space between operators). The `:` means a **type ascription** is being done. The `_*` is a special instance of type ascription: a **vararg expansion**. – José Andias Jul 05 '18 at 09:59