The notion of "same type" always depends on a level of generality. In Scala, the level of generality is determined by formal type.
Are 3 and 7 "of the same type"? If we write...
val a : Int = 3
val b : Int = 7
then they of of the same type Int
. But, if we define bit-length restricted Int
types (which we are very welcome to do in Scala), we might write
val a : Int2 = 3
val b : Int3 = 7
and they no longer appear to be of the same type!
If we define an inheritance hierarchy
trait Animal;
class Dog extends Animal;
class Frog extends Animal;
then do Dog
and Frog
have the same type? If we write
val d : Dog = new Dog
val f : Frog = new Frog
then it looks like the answer is no. But if we write
val d : Animal = new Dog
val f : Animal = new Frog
then they look like they do have the same type. Consistent with that, if I declare an array like
val arr : Array[Dog] = Array.ofDim[Dog](5)
then I can't put a frog in it, because a frog is not a dog. But if I declare the a similar array
val arr : Array[Animal] = Array.ofDim[Animal](5)
Then of course both frogs and dogs can go in it, because at the level of generality of Animal
, both Frogs and Dogs do have the same type.
In Scala Any
is a base type from which all other types derive. So, at a very high level of generality, 5
, "hello"
, and 1.5
, all have the same type Any
, just as at a high level of generality Frog
and Dog
have the same type Animal
. So there's no problem putting 5
, "hello"
, and 1.5
into an Array[Any]
.