質問

Why this code doesn't work:

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

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

But this is OK:

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

res1: scala.collection.immutable.Set[AnyVal] = Set(1, 4, 8, 1.5)

So?

役に立ちましたか?

解決

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

For more reference: reference §6.26.4. A similar question.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top