Type-classes ahead!
When creating type-classes to solve problems, such as providing a mechanism to encode types in a particular format, we have to unleash the power of languages such as Scala. What we desire is a way to encode values of a certain type in comma-separated value (CSV) format. For that purpose, we'll create a type-class named CSVEncoder
. In Scala, we can do this using a trait of some type by convention:
trait CSVEncoder[T]{ def encode(value: T): List[String] }
What we defined is a functionality provider for our types. The functionality right now is to encode a value of some particular type and give back a list of string values that we can represent in CSV. Now, you might want to use this functionality by calling some functions on it, right? For a simple type such as Person
, it can look like this:
case class Person(name: String) CSVEncoder.toCSV(Person("Max"))
Some other syntax might look like this:
Person("Caroline").toCSV
To use something like these, what we need is this...