2
votes
  1. List("a"->1, "b"->2) match { case List( k->v ,_*) => println(k) }
    error: not found: value ->
  2. List("a"->1, "b"->2) match { case List( (k,v) ,_*) => println(k) }
    success

  3. Map("a"->1, "b"->2) match { case Map( (k,v) ,_*) => println(k) }
    error: value Map is not a case class, nor does it have an unapply/unapplySeq member

Could you explain why that the left hand side succeeds using arrow ->; while at right hand side the -> failed.
If I change it to real type Tuple (k,v), then it success.
However, failed again if using Map . I cannot image Scala didn't implement unapply for Map?!


EDIT: what I thought is :: can be use in pattern matching; so could -> .
OK , now -> is a method , so cannot be matched. Scala is not intuitive.

1
What do you feel unapply shouild do on a Map? For a List, there's an ordering so it's clear what to match. For a Map, there isn't.The Archetypal Paul

1 Answers

2
votes

The -> syntax is just a shorthand to create a tuple. So 'a' -> 1 actually returns something of type (Char, Int). Since it is not a type, you can't match that syntax. Match the tuple instead.

Also for the Map, I'm not sure there is an extractor for that. You generally need and unapplySeq method, which is defined as returning a sequence. The very syntax _* means passing a sequence of parameters, and map is kind of by definition an unordered structure. You can always use toSeq to get a sequence of tuples.