Liu Renjie
Liu Renjie

Reputation: 220

What's wrong with this piece of scala code?

I have the following code snippet which can not be compiled:

val cids = List(1, 2, 3, 4)
val b = Map.newBuilder[Int, Int]
for (c <- cids) {
  b += (c, c*2)
}
b.result()

Compiler reports that

console>:11: error: type mismatch;
 found   : Int
 required: (Int, Int)
               b += (c, c*2)

I have no idea what's the mistake.

Upvotes: 1

Views: 116

Answers (5)

elm
elm

Reputation: 20415

An approach using (immutable) values,

(cids zip cids.map(_ * 2)).toMap

Using zip we pair each value with its double, and the resulting list is converted to a Map.

Upvotes: 2

som-snytt
som-snytt

Reputation: 39577

This is a duplicate question.

Normally, supplying an untupled arg list works as shown, but it doesn't work when the method is overloaded, because it will choose the method you didn't intend, and not bother to try auto-tupling your args.

scala> class C[A] { def f(a: A) = 42 }
defined class C

scala> val c = new C[(String, Int)]
c: C[(String, Int)] = C@3a022576

scala> c.f("1", 1)
res0: Int = 42

scala> class C[A] { def f(a: A) = 42 ; def f(a: A, b: A, rest: A*) = 17 }
defined class C

scala> val c = new C[(String, Int)]
c: C[(String, Int)] = C@f9cab00

scala> c.f("1", 1)
<console>:14: error: type mismatch;
 found   : String("1")
 required: (String, Int)
       c.f("1", 1)
           ^

Upvotes: 2

Som Bhattacharyya
Som Bhattacharyya

Reputation: 4112

If you go to the documentation you will find : this

The supported API is ms += (k -> v) . That is you need to use

for (c <- cids) {
  b += (c -> c*2)
}

Alternately you could use the ((c, c*2)) syntax as suggested above. This is happening because the compiler has no way of knowing that the parentheses are for the tuple. It simply understands that argument as two parameters being passed to the += method.

Upvotes: 0

Nyavro
Nyavro

Reputation: 8866

You can fix it the following way:

b += (c->c*2)

Upvotes: 5

Tzach Zohar
Tzach Zohar

Reputation: 37822

This would work:

for (c <- cids) {
   b += ((c, c*2))
}

The parenthesis are parsed by compiler as the argument-list parenthesis of the += function, and not as a tuple. Adding nested parenthesis means a tuple is passed as the argument. It is confusing...

Upvotes: 7

Related Questions