Encoding entire collections

While kantan.csv was written with large amount of data in mind - or at least, more data than a standard laptop can comfortably fit in memory - it’s still fairly common to have a collection that needs to be written down as CSV.

This is something that kantan.csv attempts to make as straightforward as possible. First, let’s define some CSV data that needs to be serialized (see this if you’re not clear what the following code is for):

import kantan.csv._
import kantan.csv.ops._
import kantan.csv.generic._

case class Person(id: Int, name: String, age: Int)

val ps = List(Person(0, "Nicolas", 38), Person(1, "Kazuma", 1), Person(2, "John", 18))

All types that support the asCsvWriter method also support writeCsv, which takes a collection of values and writes them directly as CSV:

// File in which we'll be writing the CSV data.
val out = java.io.File.createTempFile("kantan.csv", "csv")

// Writes ps using , as a column separator and with a header row.
out.writeCsv(ps, rfc.withHeader("Id", "Name", "Age"))

writeCsv takes three value arguments:

Now that we have serialized our data, let’s make sure it comes out the way we expected:

scala.io.Source.fromFile(out).mkString
// res1: String = """Id,Name,Age
// 0,Nicolas,38
// 1,Kazuma,1
// 2,John,18
// """

Note that the need for turning a collection into a CSV string is so common that kantan.csv has a special helper for that: asCsv. For example:

ps.asCsv(rfc.withHeader("Id", "Name", "Age"))
// res2: String = """Id,Name,Age
// 0,Nicolas,38
// 1,Kazuma,1
// 2,John,18
// """

If you want to learn more about:


Other tutorials: