在Scala中,Array和Array[Type]有什么区别?

3
我尝试编译并运行以下Scala源代码:

class People(val name: String)
class Student(studentName: String) extends People(studentName)

def getNames(array: Array[People]) = { array.map(_.name) }

getNames(Array[Student](new Student("Mike"), new Student("Tom")))

我收到了错误信息:

Name: Compile Error
Message: <console>:30: error: type mismatch;
 found   : Array[Student]
 required: Array[People]
Note: Student <: People, but class Array is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: People`. (SLS 3.2.10)
       getNames(Array[Student](new Student("Mike"), new Student("Tom")))

正如预期的那样,因为Array [Student]不是Array [People]的子类型。

然后我更新了

getNames(Array[Student](new Student("Mike"), new Student("Tom")))

为了

getNames(Array(new Student("Mike"), new Student("Tom")))

错误已经消除。因此,我想知道在Scala中,Array和Array [Type]之间有什么区别,特别是当它作为方法参数传递时。
提前致谢!
1个回答

1
这是因为Scala数组没有Java中的协变错误。在Java中,您可以执行以下操作:
Student[] students = new Student[10];
Person[] people = students; // ok in Java arrays are covariant
people[1] = new Person(); // RuntimeException in Java!!

Scala比Java泛型集合等更加安全。

为了获得更好的类型安全性,您应始终使用特定版本的集合。您的Array示例从函数调用中检测到通用参数 - 即Array [Student]


非常感谢您的回答,确实有所帮助! - ihainan
很抱歉,但是这个答案的第二部分是错误的。你得到的不是一个“非泛型”数组,而是一个Array[People],因为表达式的预期类型由getNames方法提供。 - Joe Pallas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接