Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Without knowing the details of design choices in the collections library I think I can see two uses here:</p> <ol> <li><p>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.</p></li> <li><p>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.</p></li> </ol> <p>Here are some examples of how it might be useful:</p> <blockquote> <pre><code>scala&gt; val a: Traversable[Int] = Set(1,2,3,4) a: Traversable[Int] = Set(1, 2, 3, 4) scala&gt; a.companion(1,2,3) res1: Traversable[Int] = Set(1, 2, 3) scala&gt; val b: Traversable[Int] = List(1,2,3,4) b: Traversable[Int] = List(1, 2, 3, 4) scala&gt; b.companion(1,2,3) res2: Traversable[Int] = List(1, 2, 3) scala&gt; def ends[T](c: Traversable[T]) : Traversable[T]= { | c.companion(c.head, c.last) | } ends: [T](c: Traversable[T])Traversable[T] scala&gt; ends[Int](List(1,2,3,4,5)) res3: Traversable[Int] = List(1, 5) scala&gt; ends[Int](Set(1,2,3,4,5)) res4: Traversable[Int] = Set(5, 4) </code></pre> </blockquote> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload