title: Scala: "map" vs "foreach" - is there any reason to use "foreach" in practice?
body: <p>In Scala collections, if one wants to iterate over a collection (without returning results, i.e. doing a side effect on every element of collection), it can be done either with</p>
  
  <pre><code>final def foreach(f: (A) ⇒ Unit): Unit
  </code></pre>
  
  <p>or</p>
  
  <pre><code>final def map[B](f: (A) ⇒ B): SomeCollectionClass[B]
  </code></pre>
  
  <p>With the exception of possible lazy mapping(*), from an end-user perspective, I see zero differences in these invocations:</p>
  
  <pre><code>myCollection.foreach { element =&gt;
    doStuffWithElement(element);
  }
  
  myCollection.map { element =&gt;
    doStuffWithElement(element);
  }
  </code></pre>
  
  <p>given that I can just ignore what map outputs. I can't think of any specific reason why two different methods should exist &amp; be used, when <code>map</code> seems to include all the functionality of <code>foreach</code>, and, in fact, I would be pretty much impressed if an intelligent compiler &amp; VM won't optimize out that collection object creation given that it's not assigned to anything, or read, or used anywhere.</p>
  
  <p>So, the question is - am I right - and there are no reasons to call <code>foreach</code> anywhere in one's code?</p>
  
  <p><strong>Notes:</strong></p>
  
  <p>(*) The lazy mapping concept, <a href="https://stackoverflow.com/questions/12631778/scala-map-on-iterator-does-not-produce-side-effects">as throughly illustrated in this question</a>, might change things a bit and justify usage of <code>foreach</code>, but as far as I can see, one specifically needs to stumble upon a <code>LazyMap</code>, normal </p>
  
  <p>(**) If one's not <em>using</em> a collection, but <em>writing</em> one, then one would quickly stumble upon the fact that <code>for</code> comprehension syntax syntax is in fact a syntax sugar that generates "foreach" call, i.e. these two lines generate fully equivalent code:</p>
  
  <pre><code>for (element &lt;- myCollection) { doStuffWithElement(element); }
  myCollection.foreach { element =&gt; doStuffWithElement(element); }
  </code></pre>
  
  <p>So if one cares about other people using that collection class with <code>for</code> syntax, one might still want to implement <code>foreach</code> method.</p>