就Array
而言,当没有给出初始值时,需要new
以及显式类型:
val ary = new Array[Int](5)
但是对于列表
:
val list1 = List[Int]() // "new" is not needed here.
当我添加new
时,发生错误:
scala> val list = new List[Int]()
<console>:7: error: class List is abstract; cannot be instantiated
val list = new List[Int]()
为什么会发生这种情况?
最佳答案
使用new
始终意味着您正在调用构造函数。
似乎对于类和伴生对象之间的区别存在一些混淆。
scala> new Array[Int](5)
res0: Array[Int] = Array(0, 0, 0, 0, 0)
scala> Array[Int](5)
res1: Array[Int] = Array(5)
在第一个表达式中,Array
引用类型,并且您正在调用构造函数。
第二个表达式脱糖为 Array.apply[Int](5)
,Array
引用伴生对象。
您无法编写new List
,因为错误和the doc说,List
是抽象的。
当您编写 List(5)
时,您正在调用 List
's companion object 上的 apply
方法。 .
scala> List[Int](5)
res2: List[Int] = List(5)
List
没有可以调用的构造函数,因为 List
是抽象的。 List
是抽象的,因为它是一个 cons 列表,因此 List
实例可以是 cons
和 nil
(或者, Scala 库将它们称为 ::
和 Nil
)。
但是如果您确实愿意,可以调用 ::
构造函数。
scala> new ::('a', new ::('b', Nil))
res3: scala.collection.immutable.::[Char] = List(a, b)
关于scala - Scala 中数组和列表初始化的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27351604/