Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nil for maps as like for Lists

Tags:

maps

scala

Is it possible to create Nil for maps?

I mean somethin similar to that:

List() match {
    case Nil => true
}

but with map:

Map() match {
    case NilMap => true
}

I tried to implement it, but I'm stuck:

object NilMap extends Map[Nothing, Nothin] {
    def unapply[K,V](map: Map[K,V]): Option[Map[K,V]] = 
       if(map.isEmpty) Some(map) else None

}

but id doesn't compile...

like image 225
Stu Redman Avatar asked Jan 01 '23 23:01

Stu Redman


1 Answers

This is called a Boolean extractor.

object NilMap {
  def unapply(map: Map[_, _]): Boolean =
    map.isEmpty
}

Map.empty[String, Int] match { case NilMap() => true; case _ => false } // true
Map("a" -> 10) match { case NilMap() => true; case _ => false } // false
like image 194
Luis Miguel Mejía Suárez Avatar answered Jan 09 '23 14:01

Luis Miguel Mejía Suárez