Using Type Classes to Quickly Convert Scala 3 Case Classes to CSV
Nov 2, 2021
This is just a quick note on transforming Scala case classes to comma-separated values (CSV) suitable for writing out to a files. It was inspired by this article.
Below is the transform boilerplate. You’ll need an implicit (given) Transform
type class for every type in your case class. You can paste the following in a Scala 3 repl.
Then test it with the following:
// import Transformer.{given, *} if used outside the repl
import java.nio.file.Pathscase class Demo(title: String,
count: Int,
f: Double,
location: URL,
file: Option[Path])val xs = List(
Demo("My stuff", 3, 3.148976,
URL("http://www.google.com"),
Some(Paths.get("/etc/some/file"))),
Demo("Your things", 100, 6570.0,
URL("http://www.bing.com"),
None))transform(xs)
The result will be the following CSV data:
title,count,f,location,file
My stuff,3,3.15,http://www.google.com,file
Your things,100,6570.00,http://www.bing.com,