How to expand a tuple

for instance, how to convert (1,2,3) to 1,2,3?

I ask this b/c I have this use case:

scala> case class Schema (id:Int, name:String, job:String)
defined class Schema

scala> rdd.collect
res31: Array[(Int, String, String)] = Array((1,john doe,developer), (2,rosa kim,hr team))

scala> rdd.map(x => Schema(x._1,x._2,x._3)).toDF.show
+---+--------+---------+
| id|    name|      job|
+---+--------+---------+
|  1|john doe|developer|
|  2|rosa kim|  hr team|
+---+--------+---------+

As you see, I have to expand the tuple by x._1, x._2, x._3 which is ugly.
So how to deal with this? :slight_smile:

You can use pattern matching syntax, which makes the code longer, but allows you to name your variables more clearly:

rdd.map { case (id, name, job) => Schema(id, name, job) }

If you prefer short code, you can convert the Schema.apply method (which is what is called when creating a case class instance) into a function and use the .tupled method to convert it from a function taking three arguments to a function taking a 3-tuple:

rdd.map((Schema.apply _).tupled)

Both of these have the same result. Personally, Iā€™d probably only use the latter, if there is a lot of parameters.

4 Likes