让我说我有:
def foo(i: Int, s: String)
并且:
val tuple: (Int, String) = (1, "s")
我可以将tuple
传递给foo
而无需为foo
添加包装吗?
答案 0 :(得分:2)
是的,它可能。使用.tupled
可以将lambda转换为接受元组作为参数。
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}}