title: Scala: build a Map from a List of tuples, but fail if there are contradictory entries
body: <p>I think this might be a common operation. So maybe it's inside the API but I can't find it. Also I'm interested in an efficient functional/simple solution if not.</p>
  
  <p>Given a sequence of tuples <code>("a" -&gt; 1, "b" -&gt;2, "c" -&gt; 3)</code> I want to turn it into a map. That's easy using <code>TraversableOnce.toMap</code>. But I want to fail this construction if the resulting map "would contain a contradiction", i.e. different values assigned to the same key. Like in the sequence <code>("a" -&gt; 1, "a" -&gt; 2)</code>. But duplicates shall be allowed.</p>
  
  <p>Currently I have this (very imperative) code:</p>
  
  <pre><code>def buildMap[A,B](in: TraversableOnce[(A,B)]): Option[Map[A,B]] = {
    val map = new HashMap[A,B]
    val it = in.toIterator
    var fail = false
    while(it.hasNext){
      val next = it.next()
      val old = map.put(next._1, next._2)
      fail = old.isDefined &amp;&amp; old.get != next._2
    }
  
    if(fail) None else Some(map.toMap)
  }
  </code></pre>
  
  <h3>Side Question</h3>
  
  <p>Is the final <code>toMap</code> really necessary? I get a type error when omitting it, but I think it should work. The implementation of <code>toMap</code> constructs a new map which I want to avoid.</p>