Skip to content

Instantly share code, notes, and snippets.

@lloydmeta
Last active August 24, 2018 16:46
Show Gist options
  • Save lloydmeta/7e64b26b28f4b86de1b5ba7cc3000ed3 to your computer and use it in GitHub Desktop.
Save lloydmeta/7e64b26b28f4b86de1b5ba7cc3000ed3 to your computer and use it in GitHub Desktop.
[Scala] Transforms one case class into another as long as the fields are a subset of the other via LabelledGeneric; Scastie link https://scastie.scala-lang.org/lloydmeta/ra0dvrV5Q2uxruQKoR020Q/2
@ import $ivy.{`com.chuusai::shapeless:2.3.3`}
import shapeless._, ops.hlist.Align, ops.hlist.SelectAll, SelectAll._
class Transform[T] {
// The fun stuff. Given an S, returns a T, if S has the right (subset of) fields
def apply[S, SR <: HList, TR <: HList](s: S)(
implicit
genS: LabelledGeneric.Aux[S, SR],
genT: LabelledGeneric.Aux[T, TR],
selectAll: SelectAll[SR, TR],
align: Align[SelectAll[SR, TR]#Out, TR]): T =
genT.from(align(selectAll(genS.to(s))))
}
object Transform {
// Convenience method for building an instance of `Transform`
def into[T] = new Transform[T]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment