Scala sealed trait as key on map throws mismatch error -


would me understand why not work? scala version 2.10

object colorenum {   sealed trait color   case object red extends color   case object blue extends color   case object green extends color } 

create map accepts color key , string value

val colormap = mutable.hashmap[colorenum.color, string]() 

put item on map using colorenum key

colormap.put(colorenum.red, "foo") 

this throws exception

error: type mismatch found: colorenum.red.type required: colorenum.color 

i must missing understanding of how should work.

thanks

summary:
of scala 2.11 (and preceding versions of scala 2.8) map's key type a in map[a, +b]. , map doesn't allow covariance when specifying key; i.e. notice how doesn't have plus (+) sign preceding it.

here's specific stackoverflow answer addresses details: https://stackoverflow.com/a/678637/501113

details:
trait, color, type defining map. , define 3 descendants of color trait. then, attempting insert these descendants of color trait (as opposed instance of trait itself) map. , type definition of map allows direct instances of color trait, not descendants (defined via extends or with).

you use .asinstanceof[color] when inserting descendant keys map in order conform map's type requirement key. however, warned using approach considered undesirable code smell.

bonus:
appears attempting define own typed enumeration. please @ this answer related question regarding defining enumerations in scala.


Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -