Pooya
Pooya

Reputation: 4481

Nil object in mutable Scala collections

As you know, Nil in Scala is an object of immutable collections. I have a problem with my custom mutable collection, for example

class ResourceMap extends mutable.HashMap[String, Int] {
   ....
    def -(o: ResourceMapType):ResourceMap = {

        if (....) {
             ......
        } else {
            Nil // Exception : raises the `change return type to Nil.type`
        }
    }
}

And my question is how can I return Nil in the - method?

Upvotes: 0

Views: 309

Answers (2)

Pooya
Pooya

Reputation: 4481

You can define an empty object that inherited from your class and use it when you want to use empty hashmap

for example :

private object EmptyHashMap extends ResourceMap { }

class ResourceMap extends HashMap[String, Int] {

   def -(o: Something):ResourceMap = {
      if(....){
         something
      }else{
          EmptyHashMap
      }
   }
}

Upvotes: 0

Shadowlands
Shadowlands

Reputation: 15074

Nil is the zero-length (empty) immutable List, not a general empty marker for collection types. It looks like you simply want new ResourceMap, or (if you want to clear the current map and then return it rather than just return a new empty instance): clear; this

Upvotes: 4

Related Questions