我尝试编译并运行以下Scala源代码:
错误已经消除。因此,我想知道在Scala中,Array和Array [Type]之间有什么区别,特别是当它作为方法参数传递时。
提前致谢!
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]之间有什么区别,特别是当它作为方法参数传递时。
提前致谢!
Array[People]
,因为表达式的预期类型由getNames
方法提供。 - Joe Pallas