【发布时间】:2016-12-05 16:57:38
【问题描述】:
我注意到 List 类中有一个名为“companion”的方法。它有什么作用?它的定义是“构建类 List 实例的工厂伴随对象”。
看来我可以使用 l.companion(11,12,13) 方法创建 List 的新实例,但为什么我要这样做而不是使用 List(11,12,13)?
val l = List[Int](1,2,3,4,1)
l: List[Int] = List(1, 2, 3, 4, 1)
val l2 = l.companion
l2: scala.collection.generic.GenericCompanion[List] = scala.collection.immutable.List$@6c3e1f48
//I can create new instances of a List using l2 but why would I do it this way?
val l3 = l2(100,11,123)
l3.foreach(println _)
100
11
123
res0: Unit = ()
从伴生返回的对象也可以用于创建可变集合(构建器)。但是我为什么要这样创建集合!
//create a Builder (a mutable collection) whose elements would be list of strings
val l5 = l2.newBuilder[List[String]]
l5: scala.collection.mutable.Builder[List[String],List[List[String]]] = ListBuffer()
l5+=List("h")
l5+=List("2")
println(l5)
ListBuffer(List(h), List(2))
res3: Unit = ()
【问题讨论】:
-
可能只是为了收藏库中的一些代码重用
-
也许吧。从同伴返回的对象也可用于创建可变集合(构建器),但我为什么要以这种方式创建新列表或构建器! val l5 = l2.newBuilder[List[String]] l5: scala.collection.mutable.Builder[List[String],List[List[String]]] = ListBuffer() l5+=List("h") l5+=List ("2") println(l5) ListBuffer(List(h), List(2)) res3: Unit = ()
标签: scala