折りたたみのアキュムレータ/戻り値としてcollection.Mapを使用できますか?例えばコレクションを使用します。折りたたみのマップ
:
found : scala.collection.Map[Int,Int]
required: scala.collection.immutable.Map[Int,Int]
Seq(1, 2, 3).foldLeft(collection.Map.empty[Int, Int]) { case (map, i) => map.asInstanceOf[collection.Map[Int, Int]] + (i -> i) }
なぜそれがcollection.immutable.Map
代わりのcollection.Map
の使用を強制されています
Seq(1, 2, 3).foldLeft(collection.Map.empty[Int, Int]) {
case (map, i) => map.asInstanceOf[collection.Map[Int, Int]] + (i -> i)
}
Scalaは私に次のタイプのエラーを与えますか?
編集:無意味なキャスティングは少し誤解を招くので、私は自分の意図をより明確にしたいと思います。 immutable.Map
とmutable.Map
のスーパークラスであるため、具体的にはcollection.Map
を折り返しの内側に使用しています。現実には、私はcollection.Map
を返し倍、考えるの内部で機能を使用しています:
scala> def func(map: collection.Map[Int, Int]): collection.Map[Int, Int] = map
func: (map: scala.collection.Map[Int,Int])scala.collection.Map[Int,Int]
scala> Seq(1, 2, 3).foldLeft(collection.Map.empty[Int, Int])((map, i) => map + (i -> i))
res11: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3)
scala> Seq(1, 2, 3).foldLeft(collection.Map.empty[Int, Int])((map, i) => func(map) + (i -> i))
<console>:9: error: type mismatch;
found : scala.collection.Map[Int,Int]
required: scala.collection.immutable.Map[Int,Int]
Seq(1, 2, 3).foldLeft(collection.Map.empty[Int, Int])((map, i) => func(map) + (i -> i))
^
下記の答えは、作業を行います。collection.Map[Int, Int]()
にcollection.Map.empty[Int, Int]
から開始値を変更します。これはしかし違いがなぜ私はわからない:
scala> Seq(1, 2, 3).foldLeft(collection.Map[Int, Int]())((map, i) => func(map) + (i -> i))
res13: scala.collection.Map[Int,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3)
これは実際には機能しません。私はfold.Mapを使用していることを説明するためにキャストが非常に重要です。私はもう少し明確にするために質問を更新します。奇妙だ – jkoenig
@jkoenigは、それは...私には完全にちょうどこのようにそれが書かれたように動作 –
動作しますが、それは私が何を意味するかの例については、[編集]をチェックし、私が本当に欲しいものであるcollection.Mapでは動作しません。あなたの答えをありがとう、私の意図をより容易に明らかにしないことに対する私の謝罪。 – jkoenig