Reputation: 133
I'm new to Scala, and I'm trying to convert this for loop from Java:
for(int x=1, y=2; x<=5; x++, y+=2)
System.out.println(x+y);
I'm trying to zip the values in Scala since I can't find a way to have multiple counters which are non-nested:
val a = Seq(1 to 5)
val b = Seq(2 to 10 by 2)
for((x,y) <- a.zip(b))
println(x+y)
But the above code is giving this error:
type mismatch; found: scala.collection.immutable.Range required: String
Does anyone know how to fix this? I would prefer to do with for loop only, not while loop.
Upvotes: 2
Views: 760
Reputation: 4328
In your example you want x
to range from 1
to 5
and y
is always 2*x
. Using for loops is easy for those coming from Java:
for(x <- 1 to 5; y = x*2) {
println(s"x = $x, y = $y, x+y = ${x+y}")
}
Here is solution to a more generic problem - iterating over elements in a collection using multiple counters (=indices or pointers), like if you want to compare each 2 pairs:
val c = List("a", "b", "c", "d") //or any collection
val end = c.length - 1
for(i <- 0 to end-1; j <- i+1 to end)
//compare or operate with each pair
println(c(i)+c(j))
... prints:
ab
ac
ad
bc
bd
cd
Upvotes: 0
Reputation: 2452
Try this, no need to wrap the Range
in a Seq
:
val a = 1 to 5
val b = 2 to 10 by 2
for(
(x,y) <- a.zip(b)
)
println(x+y)
Upvotes: 2
Reputation: 51271
You might try . . .
((1 to 5) zip (2 to 10 by 2)).foreach(x => println(x._1+x._2))
Because Scala for
comprehensions are sufficiently different from for()
loops in other languages, it's often a good idea for beginners to avoid them until they've gained a sufficient knowledge of map
, flatMap
, and foreach
.
Upvotes: 2