Scala 中 hashmap forall() 方法的示例?
有人可以举例说明如何使用 HashMap forall() 方法吗?我发现 Scala 文档难以理解。
我想要的是这样的:
val myMap = HashMap[Int, Int](1 -> 10, 2 -> 20)
val areAllValuesTenTimesTheKey = myMap.forall((k, v) => k * 10 == v)
但这给出了:
error: wrong number of parameters; expected = 1
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是forall
想要一个接受单个 Tuple2 而不是两个参数的函数。 (当我们使用
forall
时,我们将Map[A,B]
视为Iterable[(A,B)]
。)使用 case 语句是一个很好的解决方法;它实际上是在这里使用模式匹配来分解Tuple2
并给出各个部分的名称。如果你不想使用模式匹配,你也可以写,
但我认为这没什么帮助。
You need instead
The problem is that forall wants a function that takes a single
Tuple2
, rather than two arguments. (We're thinking of aMap[A,B]
as anIterable[(A,B)]
when we useforall
.) Using a case statement is a nice workaround; it's really using pattern matching here to break apart theTuple2
and give the parts names.If you don't want to use pattern matching, you could have also written
but I think that's less helpful.
forall
传递单个(Int, Int)
元组(而不是多个参数)。考虑这个(它明确地显示单个元组值被分解):或者,简写(实际上传递一个 PartialFunction):(
它们都分解接收的元组。)
此外,该函数可以被“tupled”ed:
Happy编码。
forall
is passed a single(Int, Int)
Tuple (as opposed to multiple parameters). Consider this (which explicitly shows a single tuple value is decomposed):Or, the short-hand (which actually passes a PartialFunction):
(These both decompose the tuple take in.)
Additionally, the function can be "tupled"ed:
Happy coding.
您的代码的问题在于,您为
forall
方法提供了一个函数,该函数接受 2 个参数并返回Boolean
,或者换句话说(Int, Int) = >布尔值
。如果您查看文档,那么您会发现这个签名:在本例中,
forall
方法需要Tuple2[A, B] =>; Boolean
,所以它也可以这样写:为了修复您的示例,您可以调用
forall
并为其提供接受 1 个元组参数的函数:或者您使模式匹配并提取键和值:
在本例中,您将
PartialFunction[(Int, Int), Boolean]
赋予forall
方法The problem with your code, is that you give
forall
method a function, that accepts 2 arguments and returnsBoolean
, or in other words(Int, Int) => Boolean
. If you will look in the documentation, then you will find this signature:in this case
forall
method expectsTuple2[A, B] => Boolean
, so it also can be written like this:In order to fix your example you can either call
forall
and give it function, that accepts 1 tuple argument:or you make patterns match and extract key and value:
In this case you are giving
PartialFunction[(Int, Int), Boolean]
to theforall
method