Yeah, I know this is a .NET blog, but recently my team at Ginger Software ventured into some Android coding. Now, we didn’t want to use Java, and preferred something with more functional capabilities. Scala was the natural choice. One thing we use a lot in our C# projects is CSV files. They are much easier to programmatically read/write than Excel files, and our analysts can still work with them as if they were Excel files. Sadly, Scala was missing a library to read/write CSV files to/from objects, which was something we sorely missed. Therefore, I set out to build our own. This is not a fully fledged framework, it is tailored to our specific needs, but can be easily modified to suit your own. It uses the scala-csv project as a dependency, and we call it object-csv.
Let’s say you defined this case class:
case class Person (name: String, age: Int, salary: Double, isNice:Boolean = false)
You can write a collection of Person to a .csv file this way:
import com.gingersoftware.csv.ObjectCSV._ //... val person1 = new Person("Doron,y",10,5.5) val person2 = new Person("David",20,6.5) writeCSV(IndexedSeq(person1,person2), fileName)
val peopleFromCSV = readCSV[Person](fileName) assert(peopleFromCSV === IndexedSeq(Person("Doron,y",10,5.5),Person("David",20,6.5)))
Nice and simple, right? It serves our needs nicely, but it comes with some caveats:
1) It only works with Scala 2.11, as it uses scala.reflect which wasn’t really stable on 2.10. So make sure you have set scalaVersion := “2.11.0” in your build.sbt.
2) It only works with case classes, as all the reflection stuff is based on using your case class primary constructor.
3) For reading, we only currently support the following data types: Int, Double, Boolean and String. We’ll probably add more as we need them. Writing works with everything, as we just .toString it all.
4) We can only read/write CSV files with headers, and the header must begin with the comment mark (#).
5) The API currently doesn’t expose ways to control the type of separator used in the CSV file, but it is very easy to add (the scala–csv project does support it).
6) We didn’t test it for speed, reading is likely to be slow as it uses reflection heavily.
libraryDependencies += "com.gingersoftware" % "object-csv_2.11" % "0.1"
Or you can just browse the code and copy the classes (there are only 2) to your project. We’d appreciate any feedback, we’re pretty new to Scala development.