Skip to content

Instantly share code, notes, and snippets.

@caente
Last active December 9, 2015 21:43
Show Gist options
  • Save caente/063aa9d13730d85ba0eb to your computer and use it in GitHub Desktop.
Save caente/063aa9d13730d85ba0eb to your computer and use it in GitHub Desktop.
extracting fields from case classes
import shapeless._
import ops.{ hlist => hl, coproduct => cp }
object FlexibleTypes2 {
/*
it extracts the values of a common type from a hierarchy of case classes
*/
object ints extends Poly1 {
implicit def caseProduct[T, L <: HList, S <: HList, P <: HList](
implicit
gen: Generic.Aux[T, L],
p: hl.Partition.Aux[L, Int, P, S],
tr: hl.ToTraversable.Aux[P, List, Int]
) = at[T]( t => gen.to( t ).filter[Int].to[List] )
implicit def caseCoproduct[T, L <: Coproduct, R <: Coproduct](
implicit
gen: Generic.Aux[T, L],
mapper: cp.Mapper.Aux[this.type, L, R],
unifier: cp.Unifier[R]
) = at[T]( t => gen.to( t ).map( ints ).unify )
}
sealed trait F
case class A( i: Int ) extends F
case class B( s: String ) extends F
case class C( i: Int, s: String ) extends F
val fs: List[F] = List( A( 1 ), B( "b" ), C( 3, "c" ) )
assert( fs.map( f => ints( f ) ).flatten == List( 1, 3 ) )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment