zipping case classes in scala
Let’s say we have a Scala method that takes an input param of Map[String, Any]
, where String
is a DB column name and Any
is the value.
However the data we need to insert into the DB is in the format of a Scala case class.
How do we convert the case class to a Map for DB insertion?
First let’s compare the input and output:
Existing data structure:
What our DB service requires:
So let’s do the conversion.
Since Scala case classes extend the Product
trait, our method signature will accept a Product, and depend on its productIterator
implementation.
To obtain the “keys” for our map, we will use some standard Java reflection methods:
To obtain the “values” for our map, we will use the productIterator
method that our class class implements based on it extending the Product
trait:
Now we have extracted our values, we need to zip
them together into a map.
Now we can perform the conversion.