映射 Map 时 Scala 不匹配

发布于 2024-12-25 19:20:26 字数 619 浏览 0 评论 0原文

我正在使用 Scala (2.9.1) 迈出第一个有趣的步骤(非 hello-world 级别),但我一直在试图理解一条非常无信息的错误消息。 它很像这样:

error: type mismatch;
found   : (Int, Array[InputEntry]) => (Int, Double)
required: (Int, Array[InputEntry]) => ?
entries.groupBy(grouper).map((k: Int, ies: Array[InputEntry]) => (k, doMyStuff(ies)))

正如您所猜测的,此代码片段中的进程应该是进行某些处理的地方,它实际上是一个定义良好的函数,其签名为 Array[InputEntry] =>;双倍

相反,Grouper 的签名是 Array[InputEntry] =>整数。

我尝试提取一个函数并替换 lambda,但它没有用,而且我一直试图理解错误中的问号......

有什么想法吗?

编辑:我应该澄清一下,InputEntry是我定义的一个类,但就这个例子而言,在我看来它几乎不相关。

I'm taking my first interesting steps (non-hello-world level) with Scala (2.9.1) and I'm stuck trying to understand a very uninformative error message.
It goes much like this:

error: type mismatch;
found   : (Int, Array[InputEntry]) => (Int, Double)
required: (Int, Array[InputEntry]) => ?
entries.groupBy(grouper).map((k: Int, ies: Array[InputEntry]) => (k, doMyStuff(ies)))

As you can guess process in this snippet is supposed to be where some processing goes on, and it's actually a well defined function with signature Array[InputEntry] => Double.

Grouper's signature, instead, is Array[InputEntry] => Int.

I've tried to extract a function and replace the lambda but it was useless, and I'm stuck trying to understand the question mark in the error...

Any ideas?

Edit: I should clarify that InputEntry is a class I've defined, but for the sake of this example it seems to me like it's hardly relevant.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撩人痒 2025-01-01 19:20:26

这看起来像问题:

.map((k: Int, ies: Array[InputEntry]) => (k, doMyStuff(ies)))

您需要使用 case 语句来取消应用参数并将它们分配给局部变量。您还需要使用 {} 而不是 (),因为它现在是匿名函数。

entries.groupBy(grouper).map{case (k, ies) => (k, doMyStuff(ies))}

这是一个更简单的例子。

scala> val x = List(("a",1),("b",2))
x: List[(java.lang.String, Int)] = List((a,1), (b,2))
scala> x.map{ case (str, num) => num }
res5: List[Int] = List(1, 2)

如果您不想使用 case 语句,则必须将元组保留为单个变量。

scala> x.map(tuple => tuple._2)
res6: List[Int] = List(1, 2)

This looks like the problem:

.map((k: Int, ies: Array[InputEntry]) => (k, doMyStuff(ies)))

You need to use a case statement to unapply the params and assign them to local variables. You also need to use {} instead of () because it is an anonymous function now.

entries.groupBy(grouper).map{case (k, ies) => (k, doMyStuff(ies))}

Here's a more simple example.

scala> val x = List(("a",1),("b",2))
x: List[(java.lang.String, Int)] = List((a,1), (b,2))
scala> x.map{ case (str, num) => num }
res5: List[Int] = List(1, 2)

If you don't want to use a case statement, you have to keep the tuple as a single variable.

scala> x.map(tuple => tuple._2)
res6: List[Int] = List(1, 2)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文