0 __的答案几乎就在那裏。如果你使Factory[A[_,_]]
是一個typeclass,你就全都設置好了。下面是名稱的示例規範:
// enable higher kinded types to prevent warnings
import scala.language.higherKinds
// our case classes
case class A[A1,A2](j:A1, k:A2)
case class B[B1,B2](j:B1, k:B2)
// Define our factory interface
trait Factory[T[_,_]] {
def make[P1,P2](p1: P1, p2: P2): T[P1,P2]
}
// Companion class makes factory easier to use
object Factory {
def apply[T[_, _]](implicit ev: Factory[T]) = ev
}
// Add implicit implementations of Factory[A]
implicit object AFactory extends Factory[A] {
def make[P1,P2](p1: P1, p2: P2): A[P1,P2] = A(p1, p2)
}
// Add implicit implementations of Factory[B]
implicit object BFactory extends Factory[B] {
def make[P1,P2](p1: P1, p2: P2): B[P1,P2] = B(p1, p2)
}
現在測試試驗工廠在REPL
scala> val a = Factory[A].make("one", 2)
a: A[String,Int] = A(one,2)
scala> val b = Factory[B].make(1, "two")
b: B[Int,String] = B(1,two)