【问题标题】:How can I call a function that takes 2 parameters with a Tuple2?如何使用 Tuple2 调用带有 2 个参数的函数?
【发布时间】:2010-08-18 02:08:07
【问题描述】:

我有这样的功能:

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

我有什么遗漏吗?

【问题讨论】:

    标签: scala tuples


    【解决方案1】:

    除了Dave's 回答之外,这也有效:

    (print _).tupled(johnsmith)
    

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

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

    在这种情况下,_ * _ 的类型已由 Function.tupled 定义。尝试使用 tupled 代替它,它不会工作,因为该函数是在 tupled 转换它之前定义的。

    对于您的特定情况,tupled 有效,因为 print 的类型是已知的。

    【讨论】:

      【解决方案2】:

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

      Function.tupled(print _)(johnsmith)
      

      【讨论】:

        猜你喜欢
        • 2015-02-03
        • 2013-09-24
        • 2018-01-11
        • 2017-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多