我尝试编译并运行以下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]之间有什么区别,特别是当它作为方法参数传递时。
提前致谢!
答案 0 :(得分:1)
这是因为Scala数组不会重复Java的covariance mistake。在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]
。