You cannot access members of an immutable collection being built from within the for comprehension.
First of all, I'm going to modify your example so it actually produces duplicates:
for (i <- Range(1,3); j <- Range(1,3)) yield (i min j, i max j)
//scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,1), (1,2), (1,2), (2,2))
For comprehensions are just syntactic sugar, so here's the equivalent using map
and flatMap
that produces the exact same result
Range(1,3).flatMap{i => Range(1,3).map{ j => (i min j, i max j)}}
As you can see, you're not actually building a single collection, but rather a collection of collections, and then merging them together as they're created. The inner map
is taking each j
in the range and mapping it to a pair, then the outer flatMap
is mapping each i
to a sequence of pairs and merging them together. If I change the flatMap
to just map
, the result is this:
Range(1,3).map{i => Range(1,3).map{ j => (i min j, i max j)}}
//Vector(Vector((1,1), (1,2)), Vector((1,2), (2,2)))
So only after the whole operation is finished can you access the result as a single collection. The result is a Vector which extends IndexedSeq[(Int, Int)]
, so you can use any of that trait's methods on the result, one of them is distinct
:
(for (i <- Range(1,3); j <- Range(1,3)) yield (i min j, i max j)).distinct
//Vector((1,1), (1,2), (2,2))