I agree that @Andreas solution with HList is a good example to solve the problem, but I still don't understand what the problem is:
def flatten(ls: List[_]): List[Int] = ls match { case Nil => Nil case (a: Int) :: tail => a :: flatten(tail) case (a: List[_]) :: tail => flatten(a) ::: flatten(tail) case _ :: tail => flatten(tail) }
Then:
println(flatten(List(List("one",9,8),3,"str",4,List(true,77,3.2))))
I see no problems with type erasure in your task, because you really don't need to check for erasable types. I intentionally skipped all erasable types in my example - to show this. The erasure type does not clear the information about the type of the list items, it only clears the information about the type of the generalized list that you have Any or _ in my case - so you don't need it at all. If I donβt miss anything, in your example the types will not be erased at all, because you still have Any almost everywhere.
source share