Scala:将函数参数作为元组传递

时间:2018-06-06 10:23:40

标签: scala functional-programming

让我说我有:

def foo(i: Int, s: String)

并且:

val tuple: (Int, String) = (1, "s")

我可以将tuple传递给foo而无需为foo添加包装吗?

2 个答案:

答案 0 :(得分:2)

是的,它可能。使用.tupled可以将lambda转换为接受元组作为参数。

Scala REPL

scala> def foo(i: Int, s: String): Int = i
foo: (i: Int, s: String)Int

scala> (foo _).tupled
res3: ((Int, String)) => Int = scala.Function2$$Lambda$226/234698513@45984654

scala> val tuple: (Int, String) = (1, "s")
tuple: (Int, String) = (1,s)

scala> (foo _).tupled(tuple)
res5: Int = 1

答案 1 :(得分:0)

type MyTuple = (Int, String) def foo(t:MyTuple) = ??? // some code val tuple = (1, "s") foo(tuple) // works 应该有用。

如果您想要更易于维护的内容,我建议您遵循:

foo

同样在val (int, string) = t 内,解开元组的最佳方法是

{{1}}