Example in Scala of hashmap forall() method?

Can someone please give an example of how to use the HashMap forall() method? I find the Scala docs to be impenetrable.

What I want is something like this:

val myMap = HashMap[Int, Int](1 -> 10, 2 -> 20) 
val areAllValuesTenTimesTheKey = myMap.forall((k, v) => k * 10 == v)

but this gives:

error: wrong number of parameters; expected = 1

You need instead

val myMap = HashMap[Int, Int](1 -> 10, 2 -> 20) 
val areAllValuesTenTimesTheKey = myMap.forall { case (k, v) => k * 10 == v }

The problem is that forall wants a function that takes a single Tuple2 , rather than two arguments. (We're thinking of a Map[A,B] as an Iterable[(A,B)] when we use forall .) Using a case statement is a nice workaround; it's really using pattern matching here to break apart the Tuple2 and give the parts names.

If you don't want to use pattern matching, you could have also written

val areAllValuesTenTimesTheKey = myMap.forall(p => p._1 * 10 == p._2 }

but I think that's less helpful.


forall is passed a single (Int, Int) Tuple (as opposed to multiple parameters). Consider this (which explicitly shows a single tuple value is decomposed):

val areAllValuesTenTimesTheKey = myMap.forall(t => t match { case (k, v) => k * 10 == v })

Or, the short-hand (which actually passes a PartialFunction):

val areAllValuesTenTimesTheKey = myMap.forall {case (k, v) => k * 10 == v}

(These both decompose the tuple take in.)

Additionally, the function can be "tupled"ed:

val myMap = Map((1,10), (2,20))
val fn = (k: Int, v: Int) => k * 10 == v
val tupled_fn = fn.tupled
val areAllValuesTenTimesTheKey = myMap.forall(tupled_fn)

myMap: scala.collection.immutable.Map[Int,Int] = Map((1,10), (2,20))
fn: (Int, Int) => Boolean =          // takes in two parameters
tupled_fn: ((Int, Int)) => Boolean = // note that it now takes in a single Tuple
areAllValuesTenTimesTheKey: Boolean = true

Happy coding.


The problem with your code, is that you give forall method a function, that accepts 2 arguments and returns Boolean , or in other words (Int, Int) => Boolean . If you will look in the documentation, then you will find this signature:

def forall (p: ((A, B)) => Boolean): Boolean

in this case forall method expects Tuple2[A, B] => Boolean , so it also can be written like this:

def forall (p: Tuple2[A, B] => Boolean): Boolean

In order to fix your example you can either call forall and give it function, that accepts 1 tuple argument:

myMap.forall(keyVal => keyVal._1 * 10 == keyVal._2)

or you make patterns match and extract key and value:

myMap.forall {case (k, v) => k * 10 == v}

In this case you are giving PartialFunction[(Int, Int), Boolean] to the forall method

链接地址: http://www.djcxy.com/p/86196.html

上一篇: Scala:覆盖返回null的通用Java方法

下一篇: HashMap forall()方法的Scala中的示例?