The identifier Array
refers to either the type or its companion object, depending on context.
scala> Array('a', 'b', 'c')
res0: Array[Char] = Array(a, b, c)
res0
is an instance of the Array
type. res0
is an object.
scala> Array
res1: Array.type = scala.Array$@1a69136
res1
is the companion object. res1
is an object. It is a singleton, meaning that there are no other objects of its type.
These two objects have different methods on them, because they're very different things.
Instances of the Array
type have the methods defined by the class. These are, naturally, the methods that operate on a particular Array
instance. For example, the length
method returns the length of the array. You need an instance to do this. It wouldn't make sense to write Array.length
because that doesn't specify which array you want the length of. But Array('a', 'b', 'c').length
is 3
.
The companion object has the methods defined by the object. These are the methods that do not require an Array
instance. Companion objects will object contain methods that create instances, as is the case for Array
. Hence Array.ofDim(2, 2)
creates a 2x2 array. That method isn't defined by the class because instances shouldn't have it. For example, it wouldn't make much sense to write Array('a', 'b', 'c').ofDim(2, 2)
, because the result (an empty 2x2 array) would have nothing to do with the instance that the method was called upon.