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
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With