我注意到List類中名爲'companion'的方法。它有什麼作用?它的定義是'構建類List實例的工廠伴侶對象'。列表中的伴侶方法
看來我可以使用l.companion(11,12,13)方法創建列表的新實例,但爲什麼我會這樣做而不是使用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] = [email protected]
//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 「) lll + =列表(」2「) println(l5) ListBuffer(List(h),List(2)) res3:Unit = –