I'm learning Scala and going through 99 Scala problems. For the following exercises:
Flatten a nested list structure. Example:
scala> flatten(List(List(1, 1), 2, List(3, List(5, 8))))
res0: List[Any] = List(1, 1, 2, 3, 5, 8)
The solution is given as
def flatten(ls: List[Any]): List[Any] = ls flatMap {
case ms: List[_] => flatten(ms)
case elements => List(elements)
}
But I was wondering why the following does not work?
def flatten[A](ls: List[List[A]]): List[A] = ls flatMap {
case ms: List[_] => flatten(ms)
case elements => List(elements)
}
IntellJ IDEA tells me the issue is with the flatten(ms)
part, saying "cannot resolve reference flatten with such a signature" and in the List
class documentation for flatten
it says "Note: The compiler might not be able to infer the type parameter".
Any ideas why the second code does not work?