scala - Map.contains with a super-type of key type -
i have case where
trait eventlike trait event extends eventlike trait api { private var map = map.empty[event, any] def contains(e: eventlike): boolean = map.contains(e) }
this doesn't work because of invariance in map's key type:
<console>:58: error: type mismatch; found : eventlike required: event def contains(e: eventlike): boolean = map.contains(e) ^
what work-around minimum performance penalty. is, don't want introduce terrible thing:
def contains(e: eventlike): boolean = e match { case e1: event => map.contains(e1) case _ => false }
is there different map
implementation (may mutable thread local) use?
you can declare map map[eventlike, any]
:
trait api { private var map = map.empty[eventlike, any] def contains(e: eventlike): boolean = map.contains(e) def add(e:event): unit = { map += (e -> ???) } }
you can still populate map event
keys only, while searching both event
, eventlike
.
upd
if don't mind using java mutable collections, can use hashmap
, accepts object argument of contains regardless of type parameters of map:
trait api { private val map = new java.util.hashmap[event, any] def contains(e: eventlike): boolean = map.containskey(e) }
Comments
Post a Comment