Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not use a filter for my Map?

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.

like image 608
John S Avatar asked Nov 27 '22 18:11

John S


1 Answers

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.

like image 101
Nick Avatar answered Dec 21 '22 07:12

Nick