Scala:解压缩元组作为参数列表的一部分

时间:2014-06-13 02:33:01

标签: scala tuples iterable-unpacking arity

我正在尝试将方法调用的元组的结果作为另一个方法的参数列表的 part 发送。

目标方法

def printResult(title: String, result: Int, startTime: Long, endTime: Long)

从方法,部分参数列表

返回
def sendAndReceive(send: Array[Byte]): (Int, Long, Long)

换句话说,我打算致电printResult(String, (Int, Long, Long))。如果方法返回签名与方法调用匹配,那么我可以使用

(printResult _).tupled(sendAndReceive(heartbeat))

这会导致语法错误

printresult("Hi", Function.tupled(sendAndReceive(heartbeat))

解决方法

我正在手动解包元组,然后在调用方法时使用它

val tuple = sendAndReceive(heartbeat)
printResult("Heartbeat only", tuple._1, tuple._2, tuple._3)

有没有更优雅的方法来解压缩并发送元组作为参数列表的一部分?

参考

Scala: Decomposing tuples in function arguments

Invoke a method using a tuple as the parameter list

Will tuple unpacking be directly supported in parameter lists in Scala?

Tuple Unpacking in Map Operations

4 个答案:

答案 0 :(得分:15)

您可以执行以下操作:

val (result, startTime, endTime) = sendAndReceive(heartbeat)
printResult("Heartbeat only", result, startTime, endTime)

答案 1 :(得分:4)

您是否附有此功能签名?

def printResult(title: String, result: Int, startTime: Long, endTime: Long)

如果是您的代码并且您可以修改它,那么您可以尝试使用currying,而不是这样:

def printResult(title: String)(result: Int, startTime: Long, endTime: Long)

然后你就可以这样执行:

printResult("Curried functions!") _ tupled(sendAndReceive(heartbeat))

答案 2 :(得分:1)

一种方法涉及元组的case类,例如像

case class Result(result: Int, startTime: Long, endTime: Long) {
  override def toString() = s"$result ($startTime to $endTime)"
}

def sendAndReceive(send: Array[Byte]): Result = {
  // body
  Result(1,2,3)
}

def printResult(title: String, res: Result) = println(title + res)

答案 3 :(得分:1)

这确实可以在不使用shapeless解压缩元组的情况下实现(并像你一样对函数进行处理):

import shapeless.syntax.std.tuple._

(printResult _).tupled("Hi" +: sendAndReceive(???))

"Hi" +: sendAndReceive(???)只是将值"Hi"添加到sendAndReceive返回的元组。

相关问题