Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement enums in scala slick 3?

This question has been asked and answered for slick 1 and 2, but the answers don't seem to be valid for slick 3.

Attempting to use the pattern in How to use Enums in Scala Slick?,

object MyEnumMapper {
  val string_enum_mapping:Map[String,MyEnum] = Map(
     "a" -> MyEnumA,
     "b" -> MyEnumB,
     "c" -> MyEnumC
  )
  val enum_string_mapping:Map[MyEnum,String] = string_enum_mapping.map(_.swap)
  implicit val myEnumStringMapper = MappedTypeMapper.base[MyEnum,String](
    e => enum_string_mapping(e),
    s => string_enum_mapping(s)
  )
}

But MappedTypeMapper has not been available since slick 1, and the suggested MappedColumnType for slick 2 is no longer available, despite being documented here.

What's the latest best practice for this?

like image 672
kbanman Avatar asked Jul 30 '15 00:07

kbanman


2 Answers

What exactly do you mean by MappedColumnType is no longer available? It comes with the usual import of the driver. Mapping an enum to a string and vice versa using MappedColumnType is pretty straight forward:

object MyEnum extends Enumeration {
  type MyEnum = Value
  val A = Value("a")
  val B = Value("b")
  val C = Value("c")
}

implicit val myEnumMapper = MappedColumnType.base[MyEnum, String](
  e => e.toString,
  s => MyEnum.withName(s)
)
like image 169
Roman Avatar answered Oct 02 '22 13:10

Roman


A shorter answer so that you don't need to implement myEnumMapper yourself:

import play.api.libs.json.{Reads, Writes}

object MyEnum extends Enumeration {
  type MyEnum = Value
  val A, B, C = Value // if you want to use a,b,c instead, feel free to do it

  implicit val readsMyEnum = Reads.enumNameReads(MyEnum)
  implicit val writesMyEnum = Writes.enumNameWrites
}
like image 37
0xbe1 Avatar answered Oct 02 '22 12:10

0xbe1