Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a case class to CSV in Scala

Is there a elegant way to convert a case class to a CSV value.

For example -

 case class Person( name : String, age : Int, gender: String, address : Option[String])

I was thinking about using macros but would like to know if there are any other alternatives.

NOTE: The case class doesn't contain any user defined fields.

like image 818
Soumya Simanta Avatar asked May 16 '15 04:05

Soumya Simanta


3 Answers

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()
like image 116
Justin Pihony Avatar answered Nov 13 '22 10:11

Justin Pihony


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.

like image 20
mariop Avatar answered Nov 13 '22 11:11

mariop


product-collections will also produce csv for you. product-collections scales pretty well; it's reflection free & compatible with scala-js.

import com.github.marklister.collections.io._
case class Foo(a:Int,b:String)
Seq(Foo(1,"hello"),Foo(2,"World")).csvIterator.mkString("\n")

res2: String =
1,"hello"
2,"World"

I'm the author of product-collections

like image 44
Mark Lister Avatar answered Nov 13 '22 09:11

Mark Lister