I'm getting a strange type mismatch error in Scala when I try to do the following:
val m = Map[String, Int]("a" -> 1, "b" -> 2, "c" -> 3)
val n = Map[String, Int]("c" -> 3, "d" -> 4, "e" -> 5)
n.filter((k: String, v: Int) => !m.contains(k))
<console>:10: error: type mismatch;
found : (String, Int) => Boolean
required: (String, Int) => Boolean
n.filter((k: String, v: Int) => !m.contains(k))
Am I doing something wrong? The type mismatch doesn't make sense here.
The actual required type is ((String,Int))
, i.e. a single argument that's a Pair[String,Int]
, but your syntax is passing two separate arguments. You can pass in a partial function instead, which uses the case
keyword to match the pair:
n.filter { case(k, v) => !m.contains(k) }
Here's a Relevant article about it.
Luigi deserves props for pointing out that filterKeys
is a more appropriate method to use here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With