Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala pattern matching on Map with arrow symbol

  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.

like image 403
WeiChing 林煒清 Avatar asked Jul 09 '26 00:07

WeiChing 林煒清


1 Answers

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.

like image 199
Daniel Langdon Avatar answered Jul 10 '26 14:07

Daniel Langdon