Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The signature of the normally-used <code>collect</code> on, say, <code>Seq</code>, is</p> <pre><code>collect[B](pf: PartialFunction[A,B]): Seq[B] </code></pre> <p>which is really a particular case of</p> <pre><code>collect[B, That](pf: PartialFunction[A,B])( implicit bf: CanBuildFrom[Seq[A], B, That] ): That </code></pre> <p>So if you use it in default mode, the answer is no, assuredly not: you get exactly one sequence out from it. If you follow <code>CanBuildFrom</code> through <code>Builder</code>, you see that it would be possible to make <code>That</code> actually be two sequences, but it would have no way of being told which sequence an item should go into, since the partial function can only say "yes, I belong" or "no, I do not belong".</p> <p>So what do you do if you want to have multiple conditions that result in your list being split into a bunch of different pieces? One way is to create an indicator function <code>A =&gt; Int</code>, where your <code>A</code> is mapped into a numbered class, and then use <code>groupBy</code>. For example:</p> <pre><code>def optionClass(a: Any) = a match { case None =&gt; 0 case Some(x) =&gt; 1 case _ =&gt; 2 } scala&gt; List(None,3,Some(2),5,None).groupBy(optionClass) res11: scala.collection.immutable.Map[Int,List[Any]] = Map((2,List(3, 5)), (1,List(Some(2))), (0,List(None, None))) </code></pre> <p>Now you can look up your sub-lists by class (0, 1, and 2 in this case). Unfortunately, if you want to ignore some inputs, you still have to put them in a class (e.g. you probably don't care about the multiple copies of <code>None</code> in this case).</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