1
votes

I have come across the terms boxing, unboxing, and type erasure a few times. I am reading the Scala puzzler book (Puzzler 22, Cast Away) and found a few statements which have confused me. For example:

Scala collections, like Java collections (except for arrays), cannot store Java primitive types directly. Because collections are generic, and generic classes are subject to type erasure, the type of collection elements is erased to AnyRef (java.lang.Object). All Scala’s value types, including Int, are AnyVals and thus need to be boxed into AnyRef wrapper types when stored in a collection. So every Scala Map[String, Int] actually contains Integer values under the covers. Reading Integer values out of a Map[String, Int] is thus what the compiler does all the time.

Question 1 - Does the above statement mean that Map[Int, String] is actually Map[Integer, String]?

Question 2 - Why are arrays different with regard to their ability to store Java primitives?

Question 3 - Does type erasure affect boxing and unboxing?

1

1 Answers

0
votes

Question 1. No in both senses. It's Map[Int, String] at compile-time, but just Map at runtime. The keys in this runtime Map are Integers... unless your program "cheats" in some way.

Question 2. Because JVM type system treats arrays specially and did long before generics existed. The quote doesn't mention this, but Array[File] and Array[String] are also different types at runtime (as opposed to List and all other collections).

Question 3. They happen at the same compilation stage (as you can see at https://typelevel.org/scala/docs/phases.html), and they certainly interact.