是的,您对scala array 的看法是正确的,并且您确实在此处存储了same type 的数据。看这个例子:
scala> val a = Array(5,"hello",1.5)
a: Array[Any] = Array(5, hello, 1.5)
我们没有看到包含integer、string 和double 的数组被创建。我们看到创建了一个array of Any。在array creation 期间,scala 编译器寻找nearest common supertype in hierarchy 以满足它可以hold elements of same type only 的Array 的属性。在这种情况下,Any 是所有类的超类型,满足条件。并且,如果编译器找不到公共超类型,数组创建将失败。
请注意,它不仅适用于 Array,也适用于存储 same types 的其他 collections。例如:List
scala> val list = List(5,"hello",1.5)
list: List[Any] = List(5, hello, 1.5)
我们在 scala 中存储不同数据类型的选项是什么?
如您所见,我们无法在List 和Array 中使用preserve the type of elements。所有元素都存储为Any。为了保留元素的类型并将它们存储在一起,scala 为我们提供了Tuple:
scala> val tuple = (5,"hello",1.5)
tuple: (Int, String, Double) = (5,hello,1.5)