Home > OS >  Scala: Set of tuples doesn't allow me to add a "straight" tuple
Scala: Set of tuples doesn't allow me to add a "straight" tuple

Time:01-22

I have this code of a mutable Hashmap with a mutable Set with tuples:

  val field = mutable.HashMap[String, mutable.Set[(Pos3, Pos3)]]()

In foreach loop I'm populating the field

scanner.combinations(2).foreach(comb => {
  val dist = s"${comb(0).dist(comb(1))}"
  field  = (dist -> (field.getOrElse(dist, mutable.Set())  = (comb(0), comb(1))))
}

which doesnot compile with message:

 found   : aoc2021.Pos3
 required: (aoc2021.Pos3, aoc2021.Pos3)
      field  = (dist -> (field.getOrElse(dist, mutable.Set())  = (comb(0), comb(1))))

However whenever I change the bare (comb(0), comb(0)) with a value-referenced tuple:

scanner.combinations(2).foreach(comb => {
  val posTuple = (comb(0),comb(1))
  val dist = s"${comb(0).dist(comb(1))}"
  field  = (dist -> (field.getOrElse(dist, mutable.Set())  = posTuple))
}

It compiles & executes nicely. I also played with (immutable.)Sets: same story. PS I know I should use idiomatic scala and ditch the side effects and foreach.

CodePudding user response:

Remember that when you do foo = x that is just sugar syntax for foo. =(x) (i.e. omit the dot and the parenthesis)
But when you do foo = (x, y) the compiler thinks you are just omitting the dot instead of passing a tuple which produces the error you were seeing.

The solution would be to use a double set of parenthesis like: ((comb(0), comb(1))) or using the -> extension method like: (comb(0) -> comb(1))


This is among the innumerable amount of reasons why I dislike the excessive amount of sugar syntax that the language allows.

  •  Tags:  
  • Related