0

When using range in Scala 2.12 and proceeding to iterate over the elements why do ints get boxed into java.lang.Integer when they are yielded? The below code allocates 10,000 Integers on the heap.

val boxedSeq = for (i <- 1 to 10000) yield i
println("Done")

If instead of yielding you print it, no Integers are created. Is the root cause that generic sequences cannot contain primitives 1?

for (i <- 1 to 10000) println(i)
println("Done")

10k Integers

Integers

Andronicus
  • 25,419
  • 17
  • 47
  • 88
jhopp994
  • 9
  • 1
  • Does this answer your question? [Why are so few things @specialized in Scala's standard library?](https://stackoverflow.com/questions/5477675/why-are-so-few-things-specialized-in-scalas-standard-library) – SwiftMango Apr 15 '20 at 15:38

1 Answers1

0

You can check:

https://docs.scala-lang.org/tutorials/FAQ/yield.html

When you are using yield with for in Scala it is translated to

.map((i) => {...})

It means that you are creating List and it has to contains objects.

When you are not using yield it is:

.foreach(i) {...}

And there you do not need any object.