1
這工作時,我試圖映射的情況下,類構造函數對元組的列表:映射元組默認參數
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中有效。有趣。
作品階2.11.6,JAVA 1.7.0_71 。 – mohit
'.map {case(x,y,z)=> MyClas(x,y,z)}'稍微好一點,但我認爲這是最好的。 –
另一種簡化代碼的方法是:'map Function.tupled(MyClas(_,_,_))' – Kolmar