从列表中的相应索引应用构造函数参数

时间:2016-04-22 11:51:03

标签: scala

假设我们有一个班级:

case class Header(a:String, b:String, c:String, d:String) //in reality its 16 arguments

val a = ("1","2","3","4") //or list. I think tuple is more useful as we can keep track of arity

我希望将元组a的所有值作为构造函数参数应用于Header。类似的东西:

Header(a._0,a._1,a._2,a._3) //or
Header.curried(a._0)(a._1)(a._2)(a._3)

由于必须手动输入参数,因此上面的锅炉板太多了。有没有办法可以简单地在循环中将tuple参数应用于构造函数中,或者基于其索引?

1 个答案:

答案 0 :(得分:3)

您可以使用tupled将案例类伴随的apply方法转换为一个函数1,该函数只需要一个包含所有需要的参数的元组:

case class Header(a:String, b:String, c:String, d:String)
val a = ("1","2","3","4")

Header.tupled(a) // -> Header(1,2,3,4)
// The above is short for the line below, the result is the same
(Header.apply _).tupled(a) // -> Header(1,2,3,4)