This is how toSet is declared:
def toSet[B >: A]: Set[B]
Converts this immutable set to a set.
In short it returns a new Set[B]
where B
can be A
or any super type of A
.
In doing xs.toSet + 1.5
you haven't explicitly declared the type B
. Hence now the type inference falls in action to determine the type. It sees xs
is set of type Int
and 1.5
is a Double. Type Inference now tries to find a type that can take Double as an argument.
The only next common type of Int and Double is AnyVal
. Hence B = AnyVal
and you get a new result set as Set[AnyVal]
. If you explicitly specify type, then it obviously fails i.e.
scala> xs.toSet[Int] + 2.4
<console>:9: error: type mismatch;
found : Double(2.4)
required: Int
xs.toSet[Int] + 2.4