Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Scala List of tuple becomes empty after for loop

I have a Scala list of tuples , "params", which are of size 28. I want to loop through and print each element of the list, however nothing is printed out. After finishing the for loop, I checked size of the list, which now becomes 0.

I am new to scala and I could not figure this out after a long time googling.

val primes = List(11, 13, 17, 19, 2, 3, 5, 7)
val params = primes.combinations(2)
println(params.size)

for (param <- params) {
  print(param(0), param(1))
}
println(params.size)



MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

combinations methods in List create an Iterator. Once the Iterator is consumed using methods like size, it will be empty.

From the docs

one should never use an iterator after calling a method on it.

If you comment out println(params.size), you can see that for loop is printing out the elements, but the last println(params.size) will remain as 0.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading