如何使用 Tuple2 调用带有 2 个参数的函数?

发布于 2024-09-14 23:26:35 字数 800 浏览 2 评论 0原文

我有一个像这样的函数:

def print(name:String, surname:String) { println(name + " " + surname) }

我还有一个 Tuple2:

val johnsmith = ("John", "Smith")

当我用 johnsmith 调用 print 时,出现以下错误:

scala> print(johnsmith)                                                       

error: not enough arguments for method print: (name: String,surname: String)Unit.
Unspecified value parameter surname.
       print(johnsmith)
            ^

有没有办法解决这个问题?我可以通过让 print 接受 Tuple2 来实现它:

def print2(t:Tuple2[String,String]) { println(t._1 + " " + t._2) }

现在我可以用任何一种方式调用它:

scala> print2(johnsmith)
John Smith

scala> print2("john", "smith")
john smith

我缺少什么吗?

I have a function like so:

def print(name:String, surname:String) { println(name + " " + surname) }

I also have a Tuple2:

val johnsmith = ("John", "Smith")

When I call print with johnsmith I get the following error:

scala> print(johnsmith)                                                       

error: not enough arguments for method print: (name: String,surname: String)Unit.
Unspecified value parameter surname.
       print(johnsmith)
            ^

Is there some way around this? I can get this to work by making print accept a Tuple2:

def print2(t:Tuple2[String,String]) { println(t._1 + " " + t._2) }

Now I can call it either way:

scala> print2(johnsmith)
John Smith

scala> print2("john", "smith")
john smith

Is there something I'm missing?

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

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

发布评论

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

评论(2

顾忌 2024-09-21 23:26:35

除了Dave的答案之外,这也有效:

(print _).tupled(johnsmith)

通常,Function.tupled最适合匿名函数和闭包与map和类似方法的组合。例如:

List("abc", "def", "ghi").zipWithIndex.map(Function.tupled(_ * _))

在本例中,_ * _ 的类型已由 Function.tupled 定义。尝试使用 tupled 来代替,但它不起作用,因为该函数是在 tupled 转换它之前定义的。

对于您的特定情况,tupled 可以工作,因为 print 的类型已经已知。

In addition to Dave's answer, this works too:

(print _).tupled(johnsmith)

Usually, Function.tupled will work best for anonymous functions and closures in combination with map and similar methods. For example:

List("abc", "def", "ghi").zipWithIndex.map(Function.tupled(_ * _))

In this case, the type for _ * _ is already defined by Function.tupled. Try using tupled for that instead and it won't work, because the function is defined before tupled converts it.

For your particular case, tupled works, since the type of print is already known.

野稚 2024-09-21 23:26:35

首先将方法转换为函数,然后将两个args的函数转换为一个元组的函数。

Function.tupled(print _)(johnsmith)

First convert the method to a function, and then convert the function of two args into a function of one tuple.

Function.tupled(print _)(johnsmith)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文