Scala Anonymous Functions

I am trying to filter a map from strings to ints in scala and I am having a strange problem.

If I put the following in the REPL:

scala> val myMap = Map("a" -> 1, "b" -> 2, "c" -> 3) myMap: scala.collection.immutable.Map[java.lang.String,Int] = | Map(a -> 1, b -> 2, c -> 3) 

So far this is normal, and it works ...

 scala> myMap.filter(_._2 > 1) res9: scala.collection.immutable.Map[java.lang.String,Int] = Map(b -> 2, c -> 3) 

but it fails ...

 scala> myMap.filter((k:java.lang.String, v:Int) => v > 1) <console>:9: error: type mismatch; found : (java.lang.String, Int) => Boolean required: ((java.lang.String, Int)) => Boolean myMap.filter((k:java.lang.String, v:Int) => v > 1) 

My question is what happens with the error message and an extra pair of parentheses? If I try to insert an additional set of parentheses, I get an error: not a formal formal parameter.

+4
source share
2 answers

myMap.filter expects a function of type Tuple2[String, Int] => Boolean , which is equivalent to ((String, Int)) => Boolean . You pass it a function of type (String, Int) => Boolean ; that is, a function that takes two arguments, not one Tuple2 .

Two ways to make it work:

  myMap.filter { case (k, v) => v > 1 } 

and

  myMap.filter(Function.tupled((k, v) => v > 1)) 

The first works by pattern matching, and the second by converting the (String, Int) => Boolean function to ((String, Int)) => Boolean .

By the way, the union of unified tuples and function argument lists was discussed. Perhaps in a future version of Scala, all functions will have one parameter (which may be a tuple).

+16
source

filter takes a function that takes only one parameter. In an expression, an expression takes two parameters. However, the element turns out to be a pair, so you might think that you can give two parameters. The correct way to post it would look something like this:

 myMap.filter (p => p._2 > 1) 

That is, I get a pair, p , and its second element must be greater than 1.

+6
source

All Articles