Reputation: 20080
I am looking for abstraction to compose typeclasses and avoid boilerplate code:
sealed trait MyTypeClass[T]{
def add(t:T, mystuff:Something)
}
object MyTypeClass {
implicit def tupled[A,B](implicit adder1: MyTypeClass [A],adder2: MyTypeClass [B]): MyTypeClass [(A,B)] = new MyTypeClass [(A, B)] {
override def add(t: (A, B), mystuff: Something): Unit = {
val (a,b) = t
adder1 add a
adder2 add b
}
}
}
Is there a boilerplate free approach ? Maybe in shapeless ?
Upvotes: 3
Views: 528
Reputation: 139038
Yep, Shapeless can help you here, with its TypeClass
type class:
trait Something
sealed trait MyTypeClass[A] { def add(a: A, mystuff: Something) }
import shapeless._
implicit object MyTypeClassTypeClass extends ProductTypeClass[MyTypeClass] {
def product[H, T <: HList](htc: MyTypeClass[H], ttc: MyTypeClass[T]) =
new MyTypeClass[H :: T] {
def add(a: H :: T, myStuff: Something): Unit = {
htc.add(a.head, myStuff)
ttc.add(a.tail, myStuff)
}
}
def emptyProduct = new MyTypeClass[HNil] {
def add(a: HNil, mystuff: Something): Unit = ()
}
def project[F, G](instance: => MyTypeClass[G], to: F => G, from: G => F) =
new MyTypeClass[F] {
def add(a: F, myStuff: Something): Unit = {
instance.add(to(a), myStuff)
}
}
}
object MyTypeClassHelper extends ProductTypeClassCompanion[MyTypeClass]
And then:
scala> implicit object IntMyTypeClass extends MyTypeClass[Int] {
| def add(a: Int, myStuff: Something): Unit = {
| println(s"Adding $a")
| }
| }
defined module IntMyTypeClass
scala> import MyTypeClassHelper.auto._
import MyTypeClassHelper.auto._
scala> implicitly[MyTypeClass[(Int, Int)]]
res0: MyTypeClass[(Int, Int)] = MyTypeClassTypeClass$$anon$3@18e713e0
scala> implicitly[MyTypeClass[(Int, Int, Int)]]
res1: MyTypeClass[(Int, Int, Int)] = MyTypeClassTypeClass$$anon$3@53c29556
See my blog post here for some additional discussion.
Upvotes: 5