Scala factory method with generics -
i have couple of objects i'm trying write factory method.
simplified, these are:
case class a[a1,a2](j:a1, k:a2) {} case class b[b1,b2](j:b1, k:b2) {}
i create method allow me pass in type, , instance of class. trying this:
class myfactory[t] { def make[k,l](p1: k, p2: l): t[k,l] = { new t(p1,p2) } }
that doesn't work (for various reacons, including 't cannot take parameters'), there elegant solution creating this?
0__'s answer there. if make factory[a[_,_]]
typeclass set. here example names standardised:
// enable higher kinded types 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 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) }
now test test factory in repl
scala> val = 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)
Comments
Post a Comment