Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Scala List with Slick (Play)?

I'm trying to store a List of integers here is what I am doing:

MODEL

case class Score(
  scoresPerTime: List[Int]
)

object Scores extends Table[Score]("SCORES"){
   def scorePerTime = column[List[Int]]("SCORE_PER_TIME")
   //...more code
}

Controller

val form = Form(
  Map(
    "scoresPerTime" -> list(number)
  )(Score.apply)(Score.unapply)
)

I get one compilation error:

.... could not find implicit value for parameter tm: scala.slick.lifted.TypeMapper[List[Int]][error]   def scorePerTime = column[List[Int]]("SCORE_PER_TIME")

How can I fix this to enter a list? or maybe try another option like a tuple, enum...

like image 811
John Avatar asked Jul 12 '13 20:07

John


1 Answers

You can do that by defining a type mapper from let's say List[Int] to String and vice-versa.

One possibility:

implicit def date2dateTime = MappedTypeMapper.base[List[Int], String](
  list => list mkString ",",
  str => (str split "," map Integer.parseInt).toList
)

I say it's a possibility 'cause I haven't tested. Not sure the fact it's returning a list will disrupt Slick. One place where it can be ambiguous are aggregate queries, where you'd want to count the number of , and not do a count(field) (which will obviously be one).

But this is completely non-relation. The relational way would be to have a new table with two fields, one foreign key referring one line at table SCORES and another field with one SCORE_PER_TIME. The foreign key should be a non-unique index so searches are fast. And slick handles this pretty well.

like image 129
pedrofurla Avatar answered Sep 24 '22 03:09

pedrofurla