Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pattern match an empty Map?

Tags:

scala

I've got a Map and I'd like to have different behavior if it's empty or not. I cannot figure out how to match an empty map. I've consulted other answers and pattern matching documentation, and I can't figure it out. I thought that Nil might work like it does for lists, but that isn't the case. I also can't seem to match against Map(), Map[String, String].empty or Map[String, String]()

myMap match {
   // doesn't work
   case Nil => false
   case _ => true
}

myMap match {
   // also doesn't work
   case Map[String, String]() => false
   case _ => true
}

The approaches in this answer seem like overkill for checking if a Map is empty. Also, the accepted answer checks if the Map contains any of the maps to be matched, which I do not think would apply in my situation

like image 533
Kyle Heuton Avatar asked Apr 29 '19 19:04

Kyle Heuton


2 Answers

Map doesn't provide any extractor with unapply()/unapplySeq() methods out of the box, so it is impossible to match key-value pairs it in pattern matching. But if you need only to match if map is empty you can:

val map = Map.empty[String, String]

val result = map match {
  case m:Map[String, String] if m.isEmpty =>  false
  case _ =>                                   true 
}

println(result)

outputs:

false
like image 97
zolotayaalexs Avatar answered Oct 18 '22 00:10

zolotayaalexs


Map doesn't have an unapply()/unapplySeq() method so it can't deconstructed via pattern matching.

As @Luis has commented, Nil is the List terminus and unrelated to Map.

like image 1
jwvh Avatar answered Oct 17 '22 23:10

jwvh