如何使用 Tuple2 调用带有 2 个参数的函数?
我有一个像这样的函数:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除了Dave的答案之外,这也有效:
通常,Function.tupled最适合匿名函数和闭包与
map
和类似方法的组合。例如:在本例中,
_ * _
的类型已由Function.tupled
定义。尝试使用tupled
来代替,但它不起作用,因为该函数是在tupled
转换它之前定义的。对于您的特定情况,
tupled
可以工作,因为print
的类型已经已知。In addition to Dave's answer, this works too:
Usually, Function.tupled will work best for anonymous functions and closures in combination with
map
and similar methods. For example:In this case, the type for
_ * _
is already defined byFunction.tupled
. Try usingtupled
for that instead and it won't work, because the function is defined beforetupled
converts it.For your particular case,
tupled
works, since the type ofprint
is already known.首先将方法转换为函数,然后将两个args的函数转换为一个元组的函数。
First convert the method to a function, and then convert the function of two args into a function of one tuple.