我正在寻找抽象来组成类型类并避免样板代码:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
有免费的样板吗?也许在无形?
是的,Shapeless可以帮助你,它的TypeClass类型类:
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]
Run Code Online (Sandbox Code Playgroud)
然后:
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
Run Code Online (Sandbox Code Playgroud)
请参见我的博客文章在这里的一些额外的讨论.
| 归档时间: |
|
| 查看次数: |
469 次 |
| 最近记录: |