Last active
December 9, 2015 21:43
-
-
Save caente/063aa9d13730d85ba0eb to your computer and use it in GitHub Desktop.
extracting fields from case classes
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 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