Converting a case class to CSV in Scala
How about implicits
and productIterator
?
implicit class CSVWrapper(val prod: Product) extends AnyVal {
def toCSV() = prod.productIterator.map{
case Some(value) => value
case None => ""
case rest => rest
}.mkString(",")
}
Person("name", 30, "male", None).toCSV()
Yes, in Scala there is a way to convert a case class to CSV without adding boilerplate at all. For instance PureCSV, based on the amazing Shapeless library, can do it:
scala> import purecsv.safe._
scala> case class Interval(start: Long, end: Long)
scala> Interval(10,20).toCSV()
res1: String = 1,10
scala> Seq(Interval(1,10),Interval(11,20)).toCSV("|")
res2: String =
1|10
11|20
Note: I'm the author of PureCSV.