Why can't I use a filter for my Card?

I get 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? Type mismatching doesn't make sense here.

+4
source share
3 answers

The actually required type is ((String,Int)) , that is, one argument, which is a Pair[String,Int] , but your syntax passes two separate arguments. Instead, you can pass a partial function that uses the case keyword to match a pair:

 n.filter { case(k, v) => !m.contains(k) } 

Here is a relevant article about this.

Luigi deserves the props by pointing out that filterKeys is a more suitable method to use here.

+14
source

A useless error message is a known bug in Scala 2.9.

What you need to say:

  found : (String, Int) => Boolean required: ((String, Int)) => Boolean 

those. you set Function2[String, Int, Boolean] when filter requires Function1[(String, Int), Boolean] .

You can use pattern matching according to tuples, as Nick shows, directly providing a tuple function, as Tomas shows, or you can turn Function2 into Function1 using a tuple using the tupled method:

 n.filter(((k: String, v: Int) => !m.contains(k)).tupled) // or n.filter(Function.tupled((k, v) => !m.contains(k))) 

But you are best using the built-in filterKeys method:

 n.filterKeys(!m.contains(_)) 
+9
source

Try the following:

 n.filter(entry => !m.contains(entry._1)) 

Where entry is a tuple containing (key, value) , so entry._1 is the key.

+4
source

Source: https://habr.com/ru/post/1399545/


All Articles