Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a tuple to a set does not work

Tags:

tuples

set

scala

scala> val set = scala.collection.mutable.Set[(Int, Int)]()
set: scala.collection.mutable.Set[(Int, Int)] = Set()

scala> set += (3, 4)
<console>:9: error: type mismatch;
 found   : Int(3)
 required: (Int, Int)
              set += (3, 4)
                  ^

scala> set += Tuple2(3, 4)
res5: set.type = Set((3,4))

Adding (3, 4) does not work - why ?

Normally, (3, 4) also represents a tuple with two elements.

like image 254
John Threepwood Avatar asked Aug 06 '12 09:08

John Threepwood


People also ask

Can tuples be added to a set?

You can also add tuples to a set. And like normal elements, you can add the same tuple only once.

How do you create a tuple from a set?

Creating a Tuple A tuple is created by placing all the items (elements) inside parentheses () , separated by commas. The parentheses are optional, however, it is a good practice to use them. A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).

Which operation is not allowed on a tuple?

Only two operations are allowed on tuple , as shown below. Operations like insert / delete at an index is not allowed. I learnt that tuple is an immutable data model. list allows insert and delete operations.


1 Answers

The issue is that it exists in the Set trait a method +(elem1: A, elem2: A, elems: A+) and the compiler is confused by it. It actually believes that you try to use this method with 2 Int parameters instead of using it with a tuple, as expected.

You can use instead: set += (3 -> 4) or set += ((3, 4))

like image 112
Nicolas Avatar answered Sep 27 '22 21:09

Nicolas