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))
为什么在上面的代码中,res2
的类型是Map[Product with Gender, Product with Gender]
而不是Map[Gender, Gender]
?为什么我提供给地图的四个条目,只添加了两个?
答案 0 :(得分:17)
1)Product
是Male
和Female
的最低级别超类。这是因为所有案例类都扩展Product
。两者都具有特征Gender
,Scala认可,所以它也包括在内。这是Scala对类型推断的最佳猜测,因为它是最具特异性的可推断类型(Map[Gender,Gender]
更为通用)。如果您希望类型为Map[Gender,Gender]
,则可以明确告诉它:
scala> val x: Map[Gender,Gender] = Map(Male -> Male, Female -> Female, Male -> Female, Female -> Male)
x: Map[Gender,Gender] = Map(Male -> Female, Female -> Male)
2)Map的本质是每个键只有一个值。当您添加Male -> Male
时,您将Male
映射到Male
。当您添加Male -> Female
时,您覆盖原始映射,以便现在Male
映射到Female
。如果你想拥有所有这些映射,那么仅仅对一个对列表更容易,因为它不会强制执行任何唯一性约束。