result.collect {case name::date::Nil => Person(name.toString, LocalDate.parse(date.toString)}
// or case List(name,date) => ...
Using Scala applicative to convert List[Object] to case class
-
22-09-2022 - |
Frage
I am writing a Scala Play Framework application that uses Datomic as a back-end database.
When I query Datomic, it returns "rows" as java.util.List
s of List
s of java.lang.Object
s. For example:
[
[ "Joe", "1970-04-15" ],
[ "Mary", "1975-06-01" ]
]
I would like to convert these to case classes in the most Scala-idiomatic way possible.
Currently my code looks like this:
import org.joda.time._
case class Person(name: String, dateOfBirth: LocalDate)
// assuming the query returns 1 row, get the row List
val row = result.iterator.next // e.g.: [ "Joe", "1970-04-15" ]
User(row.get(0).asInstanceOf[String],
LocalDate.parse(row.get(1).asInstanceOf[String]))
That's sort of ugly and error-prone.
Is there a way to use applicative functors to achieve the same thing? Are applicative functors the best way to do this? Is there a better way?
Lösung
Andere Tipps
There's a good library written by Pellucid called Datomisca which bridges the gap between Datomic(Clojure) and Scala in a type safe manner. Take a look how they do their conversions:
val entity = database.entity(entityId)
val name = entity.as[String](person / "name")
val age = entity.as[Long](person / "age")
which is taken right out from their website.