gpt4 book ai didi

scala - Scala 中的 Array 和 Array[Type] 有什么区别?

转载 作者:行者123 更新时间:2023-12-04 17:54:02 25 4
gpt4 key购买 nike

我尝试编译并运行以下 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] 之间有什么区别,尤其是当它作为方法参数传递时。

提前致谢!

最佳答案

这是因为 Scala 数组不重复 covariance mistake 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]

关于scala - Scala 中的 Array 和 Array[Type] 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45769887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com