2

I have a function like

def myFunction(i:Int*) = i.map(a => println(a))

but I have a List of Int's.

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

Desired output:
1
2
3
4

How can I programmatically convert myList so it can be inserted into myFunction?

Philip Nguyen
  • 871
  • 2
  • 10
  • 29
  • 3
    Unrelated: If you are using a side effecting function like `println` you can use `foreach` instead of `map`. – Peter Neyens Jul 11 '16 at 22:48
  • http://stackoverflow.com/a/28527971/2988 – Jörg W Mittag Jul 12 '16 at 10:40
  • Your question is not really "how to convert a `List` to a `Seq`", because the answer to that would be: call `toSeq` on the list. It's about how to invoke a varargs method when you have a `List`. – Jesper Jul 12 '16 at 11:58

1 Answers1

4

Looking at your desired input and output, you want to pass a List where a varargs argument is expected.
A varargs method can receive zero or more arguments of same type.
The varargs parameter has type of Array[T] actually.
But you can pass any Seq to it, by using "varargs ascription/expansion" (IDK if there is an official name for this):

myFunction(myList: _*)
insan-e
  • 3,883
  • 3
  • 18
  • 43