scala> val a = Array [Double] (10)
a: Array[Double] = Array(10.0)
scala> val a = new Array [Double] (10)
a: Array[Double] = Array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
Why these two expressions have different semantics?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s a bit confusing, but Scala has the notion of classes which you can create instances of, and objects, which are basically singleton instances of a class. It also has the notion of companion classes, which is a pair of a class and an object with the same name. This mechanism allows a “class” to essentially have static methods, which are otherwise not possible in Scala.
Arrayhas both a class and a companion object. Furthermore, theArrayobject has anapplymethod.applymeans you can create an object withArray(arg). But becauseArrayis a companion class, it also has a constructor that can be called via the more usual mechanism ofnew Array(arg).The issue is that
applyin the theArrayobject has different semantics than theArrayconstructors. Theapplymethod creates an array out of the specified objects, so, for example,Array(1,2,3)returns an array consisting of the objects1,2, and3. The constructors, on the other hand, take arguments that specify the size of the dimensions of the array (so you can create multidimensional arrays), and then initialize all slots to a default value.So, basically:
val a = Array [Double] (10)calls theapplymethod on theArrayobject, which creates a new array containing the given objects.val a = new Array [Double] (10)calls theArrayconstructor, which creates a new array with 10 slots, all initialized to a default value of0.0.