4

Why does an array of type Int have its entries initialised to 0, but an array of type BigInt have its entries initialised to null?

val a = new Array[Int](1)
val b = new Array[BigInt](1)
println(a.mkString())
println(b.mkString())

yields

0
null
1
  • By the way new Array[T](len) is a discouraged way to use arrays in scala. (probably, because it may lead to all sorts of confusion, as you shown in this question). Commented Jun 15, 2014 at 13:14

1 Answer 1

5

According to the scaladoc for Int:

Instances of Int are not represented by an object in the underlying runtime system.

Looking at the compiled class file, it indeed shows that the array of Ints becomes an array of int primitives in the bytecode. And int primitives have a value of 0 by default.

0  iconst_1
1  newarray int [10]
3  astore_2 [a]
4  iconst_1
5  anewarray scala.math.BigInt [16]
Sign up to request clarification or add additional context in comments.

1 Comment

This is because all so called primitives in Scala inherit from AnyVal. AnyVal is class that have exacly one field in constructor (and some more things here). So that anything that inherits from AnyVal unless you use method from declared class, during runtime is primitive. When you use declared method its instance is used. This is to eliminate overhead from using instnaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.