2017-07-14 9 views
2

折りたたみのアキュムレータ/戻り値として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.Mapmutable.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) 

答えて

1

Edit

方法をempty

()でオブジェクトを作成し、エラーの種類を持っている理由ですので、
def empty[A, B]: immutable.Map[A, B] = immutable.Map.empty 

、WIL:これを返します。あなたにリットルの戻り正しいタイプ、collection.Map[Int, Int]

def func(map: collection.Map[Int, Int]): collection.Map[Int, Int] = map 

Seq(1, 2, 3).foldLeft(collection.Map[Int, Int]())((res, i) => 
    res + (i -> i) 
) 

Map(1 -> 1, 2 -> 2, 3 -> 3)

+0

これは実際には機能しません。私はfold.Mapを使用していることを説明するためにキャストが非常に重要です。私はもう少し明確にするために質問を更新します。奇妙だ – jkoenig

+0

@jkoenigは、それは...私には完全にちょうどこのようにそれが書かれたように動作 –

+0

動作しますが、それは私が何を意味するかの例については、[編集]をチェックし、私が本当に欲しいものであるcollection.Mapでは動作しません。あなたの答えをありがとう、私の意図をより容易に明らかにしないことに対する私の謝罪。 – jkoenig

3

すでにタイプ定義したので、あなたは、それをキャストする必要はありません。

Seq(1, 2, 3).foldLeft(collection.Map[Int, Int]()) { 
    case (map, i) => map + (i -> i) 
} 
+0

キャストはちょうどcollection.Mapの代わりimmutable.Mapを使用するようにコンパイラに強制することでした。不思議なことに、単に – jkoenig

+0

Scalaのコレクションは、デフォルトでは不変ですけれども '作品)(' collection.Map [INT、INT]に 'collection.Map.empty [INT、INT]'から変更します。変更可能なバージョンにアクセスするには、私は不変と可変地図のスーパークラスをしたいので、私はcollection.Mapについて、具体的聞いてるのよ、私は彼らが知っているscala.collection.mutable._ – sheunis

+0

をインポートする必要があります。私は質問を短く明確にするためにこの情報を残しましたが、私の意図をより明確にするために追加します。 – jkoenig

関連する問題