简体   繁体   中英

Passing a list as varargs Scala

How can I pass a List[Any] of List[Any] 's as parameters to List.concat ? My code is:

List.concat((a filter (x => x.getClass == a.getClass)): _*)

Where a is a List[Any] and (a filter (x => x.getClass == a.getClass)) should become a list of lists. The error I get is type mismatch; found List[Any] required: Seq[Traversable[Any]] type mismatch; found List[Any] required: Seq[Traversable[Any]] .

Is there any to pass the elements of a list of parameters, or convert a list to a sequence? Thank you.

What's your intention with : _* ? Remove it and your code should work.

You can actually pass List[Any] to concat, as following.

val list1 = List("Abby", "Jim", "Tony")
val list2 = List[Any](90,"Tom")
val ret = List.concat(list1,list2)

The problem of your code, I guess is with : _* . And another problem is a filter (x => x.getClass == a.getClass) , there is a small chance that an element is the same type as the container, List in your case. Is this your real intention? You want a List[Any] contains elements with type List[Any]?

Following code works, and I verified them in http://scalass.com/tryout .

val list = List[Any](90,"Tom")
val r = List.concat((list filter (x => x.getClass == "".getClass)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM