假设我们有一个班级:
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参数应用于构造函数中,或者基于其索引?
答案 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)