KarateKid
KarateKid

Reputation: 3436

Using zipped collections to initialize a case class in scala

I have to generate a collection of object from some collections of primitive types. So I tried the following two methods and both work:

case class Gr (x:Int,y:Int, z:Int)

val x = List(1,2,4,2,5)
val y = Array(1,2,7,4,5)
val z = Seq(1,2,4,8,5)


(x,y,z).zipped.toList.map(a => Gr(a._1,a._2,a._3))
(x,y,z).zipped.map(Gr:(Int,Int,Int) => Gr) 

So, which one is better and how does the second one actually work ? And is there a better way ?

Upvotes: 2

Views: 337

Answers (1)

jwvh
jwvh

Reputation: 51271

The 1st one can be reduced to (x,y,z).zipped.toList.map(Gr.tupled) and 2nd can be reduced to (x,y,z).zipped.map(Gr), which seems to be shorter/clearer to me.


Recall that the argument to map() is, essentially, A => B, so instead of writing ds.map(d => Math.sqrt(d)), which is type Double => Double, we can simply write ds.map(Math.sqrt) because sqrt() is the correct type.

In this case, the Gr constructor is type (A,A,A) => B. The Scala compiler is able to take the output of zipped and match the constructor type, so the constructor can be used as the argument to map().

Upvotes: 6

Related Questions