Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The answer is found on the definition of <code>map</code>:</p> <pre><code>def map[B, That](f : (A) =&gt; B)(implicit bf : CanBuildFrom[Repr, B, That]) : That </code></pre> <p>Note that it has two parameters. The first is your function and the second is an implicit. If you do not provide that implicit, Scala will choose the most <em>specific</em> one available. </p> <p><strong>About <code>breakOut</code></strong></p> <p>So, what's the purpose of <code>breakOut</code>? Consider the example given for the question, You take a list of strings, transform each string into a tuple <code>(Int, String)</code>, and then produce a <code>Map</code> out of it. The most obvious way to do that would produce an intermediary <code>List[(Int, String)]</code> collection, and then convert it.</p> <p>Given that <code>map</code> uses a <code>Builder</code> to produce the resulting collection, wouldn't it be possible to skip the intermediary <code>List</code> and collect the results directly into a <code>Map</code>? Evidently, yes, it is. To do so, however, we need to pass a proper <code>CanBuildFrom</code> to <code>map</code>, and that is exactly what <code>breakOut</code> does.</p> <p>Let's look, then, at the definition of <code>breakOut</code>:</p> <pre><code>def breakOut[From, T, To](implicit b : CanBuildFrom[Nothing, T, To]) = new CanBuildFrom[From, T, To] { def apply(from: From) = b.apply() ; def apply() = b.apply() } </code></pre> <p>Note that <code>breakOut</code> is parameterized, and that it returns an instance of <code>CanBuildFrom</code>. As it happens, the types <code>From</code>, <code>T</code> and <code>To</code> have already been inferred, because we know that <code>map</code> is expecting <code>CanBuildFrom[List[String], (Int, String), Map[Int, String]]</code>. Therefore:</p> <pre><code>From = List[String] T = (Int, String) To = Map[Int, String] </code></pre> <p>To conclude let's examine the implicit received by <code>breakOut</code> itself. It is of type <code>CanBuildFrom[Nothing,T,To]</code>. We already know all these types, so we can determine that we need an implicit of type <code>CanBuildFrom[Nothing,(Int,String),Map[Int,String]]</code>. But is there such a definition?</p> <p>Let's look at <code>CanBuildFrom</code>'s definition:</p> <pre><code>trait CanBuildFrom[-From, -Elem, +To] extends AnyRef </code></pre> <p>So <code>CanBuildFrom</code> is contra-variant on its first type parameter. Because <code>Nothing</code> is a bottom class (ie, it is a subclass of everything), that means <em>any</em> class can be used in place of <code>Nothing</code>.</p> <p>Since such a builder exists, Scala can use it to produce the desired output.</p> <p><strong>About Builders</strong></p> <p>A lot of methods from Scala's collections library consists of taking the original collection, processing it somehow (in the case of <code>map</code>, transforming each element), and storing the results in a new collection.</p> <p>To maximize code reuse, this storing of results is done through a <em>builder</em> (<code>scala.collection.mutable.Builder</code>), which basically supports two operations: appending elements, and returning the resulting collection. The type of this resulting collection will depend on the type of the builder. Thus, a <code>List</code> builder will return a <code>List</code>, a <code>Map</code> builder will return a <code>Map</code>, and so on. The implementation of the <code>map</code> method need not concern itself with the type of the result: the builder takes care of it.</p> <p>On the other hand, that means that <code>map</code> needs to receive this builder somehow. The problem faced when designing Scala 2.8 Collections was how to choose the best builder possible. For example, if I were to write <code>Map('a' -&gt; 1).map(_.swap)</code>, I'd like to get a <code>Map(1 -&gt; 'a')</code> back. On the other hand, a <code>Map('a' -&gt; 1).map(_._1)</code> can't return a <code>Map</code> (it returns an <code>Iterable</code>).</p> <p>The magic of producing the best possible <code>Builder</code> from the known types of the expression is performed through this <code>CanBuildFrom</code> implicit.</p> <p><strong>About <code>CanBuildFrom</code></strong></p> <p>To better explain what's going on, I'll give an example where the collection being mapped is a <code>Map</code> instead of a <code>List</code>. I'll go back to <code>List</code> later. For now, consider these two expressions:</p> <pre><code>Map(1 -&gt; "one", 2 -&gt; "two") map Function.tupled(_ -&gt; _.length) Map(1 -&gt; "one", 2 -&gt; "two") map (_._2) </code></pre> <p>The first returns a <code>Map</code> and the second returns an <code>Iterable</code>. The magic of returning a fitting collection is the work of <code>CanBuildFrom</code>. Let's consider the definition of <code>map</code> again to understand it.</p> <p>The method <code>map</code> is inherited from <code>TraversableLike</code>. It is parameterized on <code>B</code> and <code>That</code>, and makes use of the type parameters <code>A</code> and <code>Repr</code>, which parameterize the class. Let's see both definitions together:</p> <p>The class <code>TraversableLike</code> is defined as:</p> <pre><code>trait TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr] with AnyRef def map[B, That](f : (A) =&gt; B)(implicit bf : CanBuildFrom[Repr, B, That]) : That </code></pre> <p>To understand where <code>A</code> and <code>Repr</code> come from, let's consider the definition of <code>Map</code> itself:</p> <pre><code>trait Map[A, +B] extends Iterable[(A, B)] with Map[A, B] with MapLike[A, B, Map[A, B]] </code></pre> <p>Because <code>TraversableLike</code> is inherited by all traits which extend <code>Map</code>, <code>A</code> and <code>Repr</code> could be inherited from any of them. The last one gets the preference, though. So, following the definition of the immutable <code>Map</code> and all the traits that connect it to <code>TraversableLike</code>, we have:</p> <pre><code>trait Map[A, +B] extends Iterable[(A, B)] with Map[A, B] with MapLike[A, B, Map[A, B]] trait MapLike[A, +B, +This &lt;: MapLike[A, B, This] with Map[A, B]] extends MapLike[A, B, This] trait MapLike[A, +B, +This &lt;: MapLike[A, B, This] with Map[A, B]] extends PartialFunction[A, B] with IterableLike[(A, B), This] with Subtractable[A, This] trait IterableLike[+A, +Repr] extends Equals with TraversableLike[A, Repr] trait TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr] with AnyRef </code></pre> <p>If you pass the type parameters of <code>Map[Int, String]</code> all the way down the chain, we find that the types passed to <code>TraversableLike</code>, and, thus, used by <code>map</code>, are:</p> <pre><code>A = (Int,String) Repr = Map[Int, String] </code></pre> <p>Going back to the example, the first map is receiving a function of type <code>((Int, String)) =&gt; (Int, Int)</code> and the second map is receiving a function of type <code>((Int, String)) =&gt; String</code>. I use the double parenthesis to emphasize it is a tuple being received, as that's the type of <code>A</code> as we saw.</p> <p>With that information, let's consider the other types.</p> <pre><code>map Function.tupled(_ -&gt; _.length): B = (Int, Int) map (_._2): B = String </code></pre> <p>We can see that the type returned by the first <code>map</code> is <code>Map[Int,Int]</code>, and the second is <code>Iterable[String]</code>. Looking at <code>map</code>'s definition, it is easy to see that these are the values of <code>That</code>. But where do they come from? </p> <p>If we look inside the companion objects of the classes involved, we see some implicit declarations providing them. On object <code>Map</code>:</p> <pre><code>implicit def canBuildFrom [A, B] : CanBuildFrom[Map, (A, B), Map[A, B]] </code></pre> <p>And on object <code>Iterable</code>, whose class is extended by <code>Map</code>:</p> <pre><code>implicit def canBuildFrom [A] : CanBuildFrom[Iterable, A, Iterable[A]] </code></pre> <p>These definitions provide factories for parameterized <code>CanBuildFrom</code>.</p> <p>Scala will choose the most specific implicit available. In the first case, it was the first <code>CanBuildFrom</code>. In the second case, as the first did not match, it chose the second <code>CanBuildFrom</code>.</p> <p><strong>Back to the Question</strong></p> <p>Let's see the code for the question, <code>List</code>'s and <code>map</code>'s definition (again) to see how the types are inferred:</p> <pre><code>val map : Map[Int,String] = List("London", "Paris").map(x =&gt; (x.length, x))(breakOut) sealed abstract class List[+A] extends LinearSeq[A] with Product with GenericTraversableTemplate[A, List] with LinearSeqLike[A, List[A]] trait LinearSeqLike[+A, +Repr &lt;: LinearSeqLike[A, Repr]] extends SeqLike[A, Repr] trait SeqLike[+A, +Repr] extends IterableLike[A, Repr] trait IterableLike[+A, +Repr] extends Equals with TraversableLike[A, Repr] trait TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr] with AnyRef def map[B, That](f : (A) =&gt; B)(implicit bf : CanBuildFrom[Repr, B, That]) : That </code></pre> <p>The type of <code>List("London", "Paris")</code> is <code>List[String]</code>, so the types <code>A</code> and <code>Repr</code> defined on <code>TraversableLike</code> are:</p> <pre><code>A = String Repr = List[String] </code></pre> <p>The type for <code>(x =&gt; (x.length, x))</code> is <code>(String) =&gt; (Int, String)</code>, so the type of <code>B</code> is:</p> <pre><code>B = (Int, String) </code></pre> <p>The last unknown type, <code>That</code> is the type of the result of <code>map</code>, and we already have that as well:</p> <pre><code>val map : Map[Int,String] = </code></pre> <p>So,</p> <pre><code>That = Map[Int, String] </code></pre> <p>That means <code>breakOut</code> must, necessarily, return a type or subtype of <code>CanBuildFrom[List[String], (Int, String), Map[Int, String]]</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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