Other tutorials covered encoding collections, tuples and case classes as CSV rows. While those are the most common scenarios, it is sometimes necessary to encode types that are none of these.
Let’s write such a type for the purpose of this tutorial:
class Person(val id: Int, val name: String, val age: Int)
val ps = List(new Person(0, "Nicolas", 38), new Person(1, "Kazuma", 1), new Person(2, "John", 18))
We now have a List[Person]
that we’d like to encode to CSV. This is done by providing an implicit instance
of RowEncoder[Person]
- you could write it from scratch, but it’s usually simpler and more correct
to use one of the helper methods defined in the companion object.
In our case, we want encoder
:
import kantan.csv._
import kantan.csv.ops._
implicit val personEncoder: RowEncoder[Person] = RowEncoder.encoder(0, 2, 1)((p: Person) => (p.id, p.name, p.age))
kantan.csv will work out how to encode each individual field thanks to the CellEncoder
mechanism describe in a
previous post.
Let’s make sure this worked out as expected:
ps.asCsv(rfc)
// res0: String = """0,38,Nicolas
// 1,1,Kazuma
// 2,18,John
// """
If you want to learn more about:
File
into a CsvWriter