Giovanni Azua Giovanni Azua - 2 months ago 11
Scala Question

How to flatten a list of lists when the root type is List[Any]

I have code that computes the cross product of multiple lists and generates a list of lists but the root type is

List[Any]
so if I try to do:

val result : List[Any] = computedListOfLists()
// result is List(List(List(0.1, 1), a), List(List(0.1, 1), b), List(List(0.1, 2), a), List(List(0.1, 2), b), List(List(0.1, 3), a), List(List(0.1, 3), b), List(List(0.01, 1), a), List(List(0.01, 1), b), List(List(0.01, 2), a), List(List(0.01, 2), b), List(List(0.01, 3), a), List(List(0.01, 3), b), List(List(0.001, 1), a), List(List(0.001, 1), b), List(List(0.001, 2), a), List(List(0.001, 2), b), List(List(0.001, 3), a), List(List(0.001, 3), b))

result.flatten // will not compile

Answer

You cannot directly use flatten however you can define a function like this:

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

And call like this:

val l = List(
  List(List(0.1, 1), "a"),
  List(List(0.1, 1), "b"),
  List(List(0.1, 2), "a"),
  List(List(0.1, 2), "b"),
  List(List(0.1, 3), "a"),
  List(List(0.1, 3), "b"),
  List(List(0.01, 1), "a"),
  List(List(0.01, 1), "b"),
  List(List(0.01, 2), "a"),
  List(List(0.01, 2), "b"),
  List(List(0.01, 3), "a"),
  List(List(0.01, 3), "b"),
  List(List(0.001, 1), "a"),
  List(List(0.001, 1), "b"),
  List(List(0.001, 2), "a"),
  List(List(0.001, 2), "b"),
  List(List(0.001, 3), "a"),
  List(List(0.001, 3), "b"))

flatten(l)

The result would be:

List[Any] = List(0.1, 1.0, a, 0.1, 1.0, b, 0.1, 2.0, a, 0.1, 2.0, b, 0.1, 3.0, a, 0.1, 3.0, b, 0.01, 1.0, a, 0.01, 1.0, b, 0.01, 2.0, a, 0.01, 2.0, b, 0.01, 3.0, a, 0.01, 3.0, b, 0.001, 1.0, a, 0.001, 1.0, b, 0.001, 2.0, a, 0.001, 2.0, b, 0.001, 3.0, a, 0.001, 3.0, b)