LoginSignup
0
0

More than 3 years have passed since last update.

ScalaのMapの+ methodはkeyが同じ場合に上書きする

Last updated at Posted at 2020-11-11

動作確認コード

import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class ScalaMapAddPriorityTest extends AnyWordSpec with Matchers {
  "map の + method" when {
    "keyが重複" should {
      "追加したvalueで上書きされる" in {
        (Map("a" -> 1) + ("a" -> 99)).apply("a") should be(99)
      }
    }
  }

  "map の ++ method" when {
    "keyが重複" should {
      "右側のvalueで上書きされる" in {
        (Map("a" -> 1) ++ Map("a" -> 99)).apply("a") should be(99)

        (Map("a" -> 99) ++ Map("a" -> 1)).apply("a") should be(1)

        (Map("a" -> 1) ++ Map("a" -> 99) ++ Map("a" -> 555))
          .apply("a") should be(555)
      }
    }
  }
}

scala-sandbox/ScalaMapAddPriorityTest.scala at da8969f860192bf26c242aa38c4849eb9271ec21 · tksugimoto/scala-sandbox

Scaladoc

優先順位は書かれていなかった

+

  /** Add a key/value pair to this map.
   *  @param    key the key
   *  @param    value the value
   *  @return   A new map with the new binding added to this map
   */
  override def updated [V1 >: V](key: K, value: V1): Map[K, V1]
  def + [V1 >: V](kv: (K, V1)): Map[K, V1]

++

  /** Adds a number of elements provided by a traversable object
   *  and returns a new collection with the added elements.
   *
   *  @param xs      the traversable object consisting of key-value pairs.
   *  @return        a new immutable map with the bindings of this map and those from `xs`.
   */
  override def ++[V1 >: V](xs: GenTraversableOnce[(K, V1)]): immutable.Map[K, V1] =
    ((repr: immutable.Map[K, V1]) /: xs.seq) (_ + _)

+ が呼ばれているので、+ 依存

/:foldLeft

  def /:[B](z: B)(op: (B, A) => B): B = foldLeft(z)(op)

未確認事項

  • 具体的な + 実装
    • Map の実装によるのかもしれない
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0