scala> sealed trait Gender
defined trait Gender
scala> case object Male extends Gender
defined module Male
scala> case object Female extends Gender
defined module Female
scala> Map(Male -> Male, Female -> Female, Male -> Female, Female -> Male)
res2: scala.collection.immutable.Map[Product with Gender,Product with Gender] =
Map((Male,Female), (Female,Male))
Why in the above code, the type of res2 is Map[Product with Gender, Product with Gender] instead of Map[Gender, Gender]? And why of the four entries I supplied to map, only two got added?
1)
Productis the lowest-level superclass of bothMaleandFemale. This is because all case classes extendProduct. Both have traitGender, which Scala recognizes, so it includes that too. This is Scala’s best guess for type inference because it is the most specific type inferable (Map[Gender,Gender]is more general). If you want the type to beMap[Gender,Gender], you can tell it that explicitly:2) The nature of a Map is that it has only one value for each key. When you add
Male -> Maleyou are mappingMaletoMale. When you addMale -> Femaleyou are overwriting the original mapping so that nowMalemaps toFemale. If you want to have all of these mappings, then it’s probably easier to just to a list of pairs since that doesn’t enforce any uniqueness constraints.