当我尝试将一个案例类构造函数映射到元组列表时,这是有效的:
scala> case class MyClas(x:Int, y:String, z:String)
defined class MyClas
scala> Seq((1,"hey","you"), (2, "blue","shoe")) map Function.tupled(MyClas)
res1: Seq[MyClas] = List(MyClas(1,hey,you), MyClas(2,blue,shoe))
但是当类构造函数中存在默认参数时:
scala> case class MyClas(x:Int, y:String, z:String, zz:String="blue")
defined class MyClas
scala> Seq((1,"hey","you"), (2, "blue","shoe")) map Function.tupled(MyClas)
<console>:10: error: type mismatch;
found : MyClas.type
required: (Int, String, String) => ?
Seq((1,"hey","you"), (2, "blue","shoe")) map Function.tupled(MyClas)
以下作品,但感觉应该有一个更简单的方法:
scala> Seq((1,"hey","you"), (2, "blue","shoe")) map Function.tupled((x,y,z)=>MyClas(x,y,z))
res3: Seq[MyClas] = List(MyClas(1,hey,you,blue), MyClas(2,blue,shoe,blue))
编辑:哦,我忘了澄清这是Scala 2.10.4,但根据@ mohit的评论,这现在适用于Scala 2.11。有趣。
答案 0 :(得分:1)
你可以添加一个伴随对象并为Tuple4和Tuple3定义一个tupled方法:
case class MyClas(x:Int, y:String, z:String, zz: String = "blue") {
}
object MyClas {
def tupled(a: (Int, String, String)) = new MyClas(a._1, a._2, a._3)
def tupled(a: (Int, String, String, String)) = new MyClas(a._1, a._2, a._3, a._4)
}
然后这样称呼:
Seq((1, "hey", "you"), (2, "blue", "shoe")).map(MyClas.tupled)
Seq((1, "hey", "you", "blah"), (2, "blue", "shoe", "blah")).map(MyClas.tupled)