2

I am reading the Scala List API. I couldn't figure out the use for the companion function below.

def companion : GenericCompanion[List]

The factory companion object that builds instances of class List.

It seems that it is meant for some functions in List but not for the end users to consume it directly. If it is the case so, how would one know if the function is not to be consumed by the application developer directly? Of course, this is my educated assumption only and would like to be corrected if I am wrong.

2 Answers 2

4

Without knowing the details of design choices in the collections library I think I can see two uses here:

  1. DRY. Somewhat internal but having a companion object which acts as a factory building from a type specific Builder is a common pattern in the collections library so refactoring this into a class each collection implementation composes reduces duplication.

  2. Abstraction. Exposing "companion" provides a means for client code to construct a new collection of the same type as an instance without necessarily knowing what that type is. This would be useful if you want to create more general collection handling functions that return consistent types.

Here are some examples of how it might be useful:

scala> val a: Traversable[Int] = Set(1,2,3,4)
a: Traversable[Int] = Set(1, 2, 3, 4)

scala> a.companion(1,2,3)
res1: Traversable[Int] = Set(1, 2, 3)

scala> val b: Traversable[Int] = List(1,2,3,4)
b: Traversable[Int] = List(1, 2, 3, 4)

scala> b.companion(1,2,3)
res2: Traversable[Int] = List(1, 2, 3)

scala> def ends[T](c: Traversable[T]) : Traversable[T]= {
|        c.companion(c.head, c.last)
|      }
ends: [T](c: Traversable[T])Traversable[T]

scala> ends[Int](List(1,2,3,4,5))
res3: Traversable[Int] = List(1, 5)

scala> ends[Int](Set(1,2,3,4,5))
res4: Traversable[Int] = Set(5, 4)

Note that "ends" doesn't know which subtype of Traversable it receives but is able to give back a new collection of a compatible type built using the companion.

2
  • Added a simple snippet to make what I was suggesting clearer. Dec 20, 2011 at 22:28
  • Thanks! it all makes sense now! Dec 21, 2011 at 19:57
3

The idea is that a trait in the top of the hierarchy can get the companion (and the builders contained therein) so that it can build a collection of the type of the collection in the bottom of the hierarchy. Only I don't know where, exactly, it is used, since there's already a newBuilder method that provides for that.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.