Question

Because the MySQL database not support Arrays, I want to map lists of strings like List("facebook","linkedin","local") to a string like "facebook, linkedin, local".

I want do the bidirectional mapping with slick 2.0, but I do not how to write an instance of TypeMapper.

Can anyone provide an example for me?

Was it helpful?

Solution

This is documented in the official slick doc here.

You can use MappedColumnType.base[T, U](tmap: (T) ⇒ U, tcomap: (U) ⇒ T) (see scaladoc).

It requires two function arguments tmap and tcomap which do the mapping in both directions.

For your specific use case this could be implemented like such:

implicit val stringListMapper = MappedColumnType.base[List[String],String](
  list => list.mkString(","),
  string => string.split(',').toList
)

Note that this is not safe because if there are commas contained in the Strings, the mapping is not bijective. You would have to make sure there are none or escape them in some way. I leave this to you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top