Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does "for (i <- 1 to x; j <- 1 to y)" actually increment the variables in Scala?

How is below loop being incremented ?

for(i <- 1 to 3; j <- 1 to 3) print((10 * i + j) + " ")

Is there an implicit counter using 'to' ?

like image 730
user701254 Avatar asked Dec 18 '25 18:12

user701254


2 Answers

for is actually shorthand for applying a bunch of collections methods. In particular, if you are not using yield, each statement in the for selector is translated to foreach. So

for (i <- 1 to 3; j <- 1 to 4) f(i,j)

turns into

(1 to 3).foreach{ i => (1 to 4).foreach{ j => f(i,j) } }

foreach is a method on all collections--Range included, which is what 1 to 3 turns into--which loops through each item in the collection, calling a provided function each time. A Range's items are the numbers listed (endpoints included, in this case)--in fact, Range doesn't actually store the numbers in a separate list, so it's main purpose is precisely to hold ranges of numbers for exactly this sort of iteration.

like image 133
Rex Kerr Avatar answered Dec 21 '25 09:12

Rex Kerr


There is an implicit conversion from Int to RichInt.

RichInt defines the function to() which returns a Range.

Range is a collection, and has foreach() hence it can be used in a for comprehension (which is just syntactic sugar for foreach()).

like image 21
Brian Smith Avatar answered Dec 21 '25 09:12

Brian Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!