scala - Scala 中数组和列表初始化的区别

标签 scala

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 实例可以是 consnil (或者, 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/

相关文章:

android - 找不到库 "libmaliinstr.so"

Scala 枚举值未排序?

scala - scala 反射 API Type.dealias 有什么作用?

scala - map 中函数之间没有点

scala - Lift 是否使客户端 javascript 库(如 Backbone)变得多余?

eclipse - 您如何将 Eclipse 配置为自动 "run as Scala application"?

database - Scala, Play - 无法插入 Postgresql 数据库

scala - 在 Spark 中对 RDD 中的邻居元素进行操作

scala - 没有给出变量时如何确定其类型?

bash - 如何使用Spark添加HDFS数据