vendredi 28 août 2015

Using a map to fill a case class

Generic problem: I have a JSON-representation of a datastructure (which will be represented as a Map[String, Any] from now on) and a (case) class with some (!) of the key-value pairs as fields, but not all of them. I want to fill them in, with default values where the map has no pair (e.g. with constructor based default values for simplicity).

This would allow something like:

case clase User(id : Int, name : String, vegan : Boolean = false)
val map = Map("id" -> 42, "name" -> "tom")
val user = map.as[User] //User {42, "tom", false}

Coding it manually would be easy, but takes time and makes the code larger/harder to maintain/inspect (especially for >20 fields per class).

I feel like this needs to be possible by reflection, and more specifically at compile-time, without any performance detriment or problem with bytecode representation.

I know there are many questions (and answers) related to mapping maps to and from case classes, but most use deprecated apis, and the state of the art probably has progressed as well.

Aucun commentaire:

Enregistrer un commentaire