Looser coupling with type classes
So far, we have been reading and writing simple types to the database. Let's imagine that we want to add a gender
column to our database. We will store the gender as an enumeration in our physicists database. Our table is now as follows:
mysql> CREATE TABLE physicists ( id INT(11) AUTO_INCREMENT PRIMARY KEY, name VARCHAR(32) NOT NULL, gender ENUM("Female", "Male") NOT NULL );
How can we represent genders in Scala? A good way of doing this is with an enumeration:
// Gender.scala object Gender extends Enumeration { val Male = Value val Female = Value }
However, we now have a problem when deserializing objects from the database: JDBC has no built-in mechanism to convert from a SQL ENUM
type to a Scala Gender
type. We could achieve this by just converting manually every time we need to read gender information:
resultsStream.map { rs => Gender.withName(rs.getString("gender")) }.toVector
However, we would need to write this everywhere...