-
-
Save jmacias/8e21ef12b53be2cb4f51ab2ea3e45ab5 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@ 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