奇怪的scala.collection.immutable.Set添加行为

奇怪的scala.collection.immutable.Set添加行为,scala,scala-collections,Scala,Scala Collections,此代码不起作用的原因: val xs = Set(1, 4, 8) xs + 1.5 <console>:10: error: type mismatch; found : Double(1.5) required: Int xs + 1.5 那么?这是如何声明的: def toSet[B >: A]: Set[B] Converts this immutable set to a set. 简而言之,它返回一个新的集合[B],其中B可以是a或a

此代码不起作用的原因:

val xs = Set(1, 4, 8)
xs + 1.5

<console>:10: error: type mismatch;
found   : Double(1.5)
required: Int
          xs + 1.5
那么?

这是如何声明的:

def toSet[B >: A]: Set[B] 
Converts this immutable set to a set.
简而言之,它返回一个新的
集合[B]
,其中
B
可以是
a
a
的任何超级类型

在执行
xs.toSet+1.5
时,您没有明确声明类型
B
。因此,现在类型推断开始起作用,以确定类型。它看到
xs
Int
类型的集合,
1.5
是双精度的。类型推断现在尝试查找可以将Double作为参数的类型

唯一下一个常见的Int和Double类型是
AnyVal
。因此,
B=AnyVal
将得到一个新的结果集,即
set[AnyVal]
。如果显式指定类型,那么它显然会失败,即

scala> xs.toSet[Int] + 2.4
<console>:9: error: type mismatch;
 found   : Double(2.4)
 required: Int
              xs.toSet[Int] + 2.4
scala>xs.toSet[Int]+2.4
:9:错误:类型不匹配;
发现:双(2.4)
必填项:Int
xs.toSet[Int]+2.4
更多参考:§6.26.4。类似的

scala> xs.toSet[Int] + 2.4
<console>:9: error: type mismatch;
 found   : Double(2.4)
 required: Int
              xs.toSet[Int] + 2.4