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?

3
  • 3
    Unrelated: If you are using a side effecting function like println you can use foreach instead of map. Commented Jul 11, 2016 at 22:48
  • stackoverflow.com/a/28527971/2988 Commented Jul 12, 2016 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. Commented Jul 12, 2016 at 11:58

1 Answer 1

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: _*)
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. It would have taken me eons to figure this out on my own.
could you please explain your answer as well?
@ManuChadha I elaborated bit more on it. I actually expected it to be closed as duplicate... LOL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.