Tuple2 and a tuple of two elements: what are their differences?

In the following code, why did type mismatch occur?

scala> val lb = ListBuffer[Tuple2[Int, Int]]()
lb: scala.collection.mutable.ListBuffer[(Int, Int)] = ListBuffer()

scala> lb += (1, 2)
<console>:11: error: type mismatch;
 found   : Int(1)
 required: (Int, Int)
              lb += (1, 2)
                     ^

scala> lb += Tuple2(1, 2)
res43: lb.type = ListBuffer((1,2))
+5
source share
2 answers

When you write

lb += (1, 2)

In fact, you call the + = method with two integer arguments, where it must be one Tuple2 [Int, Int]:

lib.+=(1, 2)

To fix this, add another () around (1, 2), as shown below:

lb += ((1, 2))
lib.+=((1, 2))
+7
source

Brian answers correctly, but I recommend writing it like this:

lb += 1 -> 2

There is an implicit conversion from Anyto ArrowAssocthat has a method ->:

class ArrowAssoc[A](val x: A) {
    def -> [B](y: B): Tuple2[A, B] = Tuple2(x, y)
  }
+9
source

All Articles