Skip to content

Instantly share code, notes, and snippets.

@mpilquist
Created April 21, 2015 23:43
Show Gist options
  • Save mpilquist/86f65259ffe22d3879f4 to your computer and use it in GitHub Desktop.
Save mpilquist/86f65259ffe22d3879f4 to your computer and use it in GitHub Desktop.
object CaseClassToMapStringOfString {
import shapeless._
import shapeless.labelled._
import syntax.singleton._
import record._
import ops.record._
import syntax.singleton._
case class Color(value: String)
case class ChartOptions(stringOpt: String, intOpt: Int, colorOpt: Color)
private def colorToString(c: Color): String = c.value
object convertToString extends Poly1 {
implicit def forString[K] = at[String with KeyTag[K, String]](s => field[K](s))
implicit def forInt[K] = at[FieldType[K, Int]](i => field[K](i.toString))
implicit def colorToStringMapper[K] =
at[FieldType[K, Color]](field[K](colorToString _))
}
val gen = LabelledGeneric[ChartOptions]
val opt = ChartOptions("one", 2, Color("red"))
val optsRecord = gen.to(opt)
// I really want to convert to toString on type by type basis
// But once I map here, I seem to be dropping the keys so then I can't invoke toMap
// Instead of having an HList of FieldTypes, I have an HList of just String
// shapeless.::[String,shapeless.::[String,shapeless.::[String,shapeless.HNil]]]
val mappedRec = optsRecord.map(convertToString)
// toMap kind of works here, but now I am just using toString on value which is really just Any.toString
val globalMap: Map[String, String] = optsRecord.toMap.map {
case (key, value) =>
(key.name) -> value.toString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment