Reputation: 2320
I have seen this function. I created this function with generic types but I saw this solution. I don't know if type the args with Any is better or there's different.
def flatten(ls: List[Any]): List[Any] = ls flatMap {
case ms: List[_] => flatten(ms)
case e => List(e)
}
or
def flatten(ls: List[A]): List[A]
Upvotes: 1
Views: 693
Reputation: 2272
One of the differences is, when you take Any
, you lose all type information, however with generics, you still have a notion of the type.
For example, if you have a function of (Any) => Any
, you can take any type and return any type.
With generic you could however restrict that if you take an instance of T
you must also return an instance of T
, as (T) => T
.
Using generics will enable the compiler to help you check that you infact does return a List[T]
.
Upvotes: 7