gpt4 book ai didi

list - List(1,2,3) 在 Scala 中如何工作?

转载 作者:行者123 更新时间:2023-12-03 18:10:14 24 4
gpt4 key购买 nike

这在 Scala 中是如何工作的?

val something = List(1,2,3)
List是抽象的,你不能通过调用 new List() 来构造它, 但是 List(1,2,3)工作得很好。

最佳答案

因为它是对 apply 的调用列表伴随对象的方法。在 scala 中,调用 apply 的方法可以省略方法名称(即仅使用括号)。正是通过这种机制,序列和映射访问起作用

因此,List(1, 2, 3)实际上是:

List.apply(1, 2, 3)

所以这是对 List 的 companion object 的 apply 方法的调用。 , implementation of which是:
override def apply[A](xs: A*): List[A] = xs.toList

所以你可以看到 apply是一种采用重复参数(序列)的方法,并调用 toList这个序列的方法。 Seq 上的这个 toList 继承自 TraversableOnce :
def toList: List[A] = new ListBuffer[A] ++= seq toList

所以你可以看到这通过 ListBuffer 创建了一个列表。和 ++=方法:
override def ++=(xs: TraversableOnce[A]): this.type =
if (xs eq this) ++= (this take size) else super.++=(xs)

这最终实现了 ++=来自 Growable :
def ++=(xs: TraversableOnce[A]): this.type = { xs.seq foreach += ; this } 

调用 new List()不起作用,因为 List 是 trait (还有一个 sealed 那个)——你必须为抽象方法应用实现。它被密封的事实意味着它只能由同一源文件中的类实现。

关于list - List(1,2,3) 在 Scala 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7567160/

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