0

I'm currently learning Scala and running through the 99 problems (http://aperiodic.net/phil/scala/s-99/) the solution it gives to P07 (http://aperiodic.net/phil/scala/s-99/p07.scala) is as shown:

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

But when I change the _ to Any or the other way around it seems to make no difference in the result. As such I question what the difference is and why they do it this way.

Jonathan Woollett-light
  • 2,813
  • 5
  • 30
  • 58
  • 1
    Check this answer: https://stackoverflow.com/questions/15186520/scala-any-vs-underscore-in-generics – dfmarulanda Oct 10 '18 at 16:48
  • `List` is covariant, so any `List` is a `List[Any]`. So in this particular case, `List[_]` and `List[Any]` are both ways of saying "I don't care what the element type is". In other contexts, whether a type parameter is `_` or `Any` could matter very much, for example `Set` is invariant, so `Set[Any]` means a set of `Any`s, while `Set[_]` means a set of some type, perhaps a very specific type, but I don't know or care what type that is. Example: `Set[Int]` conforms to `Set[_]` but does not conform to `Set[Any]`. – Seth Tisue Oct 10 '18 at 17:10

1 Answers1

1

In short, Any is a class, like an object in Java. _is like a wildcard, and it is used to abbreviate things. In most of the cases it will work very similar, but when you think in, for example, a List[Any] you'll get a list of anything, but if you have a List[_], you'll get a list of you don't know what, it could be nothing.

dfmarulanda
  • 156
  • 1
  • 8