Search code examples
scalalanguage-featuresvariadic-functions

Programmatically setting Repeated Parameters in Scala


I'm trying to call Futures.awaitAll with a variable number of well... Futures. awaitAll is defined as awaitAll(timeout : Long, fts : Future[Any]*). I have tried passing in a List and an Array but both won't work:

list = future1 :: future2 :: Nil

Futures.awaitAll(1000, list)

found : List[scala.actors.Future[Any]] required: scala.actors.Future[Any]

EDIT: What I now want to do is call Futures.awaitAll programmatically with a variable number of arguments (1 to n). So using Futures.awaitAll(1000, future1, future2) is not an option.

Chapter 8.8 of Programming in Scala didn't give me any hints how to solve this either, so help is welcome :)


Solution

  • Using the * means that it's a vararg...it can take as many Future[Any] parameters as you add, but not a list/array of them.

    So it's looking for a parameter list such as:

    Futures.awaitAll(1000, future1, future2)
    

    instead of

    Futures.awaitAll(1000, list)
    

    Edit: If you must have the ability to pass in Futures.awaitAll(1000, list), then try casting it.

    So try this:

    Futures.awaitAll(1000, list: _*)