简体   繁体   中英

flatMap with a map in scala

Why doesn't this work:

val m = Map( 1-> 2, 2-> 4, 3 ->6)
def h(k: Int, v: Int) = if (v > 2) Some(k->v) else None
m.flatMap { case(k,v) => h(k,v) }
m.flatMap { (k,v) => h(k,v) }

The one with the case statement gives me:

res1: scala.collection.immutable.Map[Int,Int] = Map(2 -> 4, 3 -> 6)

but the other one fails and says MIssing Type parameter v , and expected: Int, actual:(Int, Int)

The case keyword signifies pattern matching, so the Tuple2 (a Map is an Iterable of Tuple2 elements) that you are flatMapping "over" gets decomposed into k and v. (The fact that flatMap works when the h function is producing an Option rather than a Map or Iterable is the Scala collections library being perhaps overly permissive.)

Without the case keyword, you are providing a function that requires two arguments, but flatMap needs a function that accepts a single argument (a Tuple2 ). So the second version does not typecheck.

对于第二篇,如果您不想使用case ,则可以执行此操作。

m.flatMap { x => h(x._1, x._2) } // x is (key,value) pair here(each element in map), hence accessing the key , value as _1,_2 respectively

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM