Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten a List of different types in Scala?

I have 4 elements:List[List[Object]] (Objects are different in each element) that I want to zip so that I can have a List[List[obj1],List[obj2],List[obj3],List[obj4]]

I tried to zip them and I obtained a nested list that I can't apply flatten to because it says: no implicit argument matching parameter type.

How can I solve this? should I try another way or is there any way to make the flatten work?

I'm kinda new to scala so it may be a dumb question :D Thanks in advance! clau

like image 866
clau Avatar asked Nov 15 '09 12:11

clau


2 Answers

For One Nested List: flatten will do:

scala> List(List(1), List(2), List(3)).flatten
res4: List[Int] = List(1, 2, 3)

scala> List(List(List(1)), List(List(2)), List(List(3))).flatten
res5: List[List[Int]] = List(List(1), List(2), List(3))

For multiple Nested Lists then you can:

def flatten(ls: List[Any]): List[Any] = ls flatMap {
  case i: List[_] => flatten(i)
  case e => List(e)
}

val k = List(1, List(2, 3), List(List(List(List(4)), List(5)), List(6, 7)), 8)
flatten(k)

It prints List[Any] = List(1, 2, 3, 4, 5, 6, 7, 8)

like image 153
Jatin Avatar answered Oct 24 '22 03:10

Jatin


Before Scala 2.9

From the error you pasted, it looks like you're trying to call the flatten instance method of the nested list itself. That requires an implicit conversion to make something of type Iterable out of whatever types the List contains. In your case, it looks like the compiler can't find one.

Use flatten from the List singleton object, which doesn't require that implicit parameter:

scala> val foo = List(List(1), List("a"), List(2.3))
foo: List[List[Any]] = List(List(1), List(a), List(2.3))

scala> List.flatten(foo)
res1: List[Any] = List(1, a, 2.3)

After Scala 2.9

Just use foo.flatten.

like image 15
Ben James Avatar answered Oct 24 '22 03:10

Ben James