Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala factory method with generics

Tags:

scala

I have a couple of objects for which I'm trying to write a factory method.

Simplified, these are:

case class a[a1,a2](j:a1, k:a2) {}
case class b[b1,b2](j:b1, k:b2) {}

I would like to create a method which would allow me to pass in the type, and get an instance of that class. I am trying to get to something like this:

class myfactory[T] {
   def make[K,L](p1: K, p2: L): T[K,L] = {
     new T(p1,p2)
   }
}

That obviously doesn't work (for various reasons, including 'T cannot take parameters'), but is there an elegant solution for creating something like this?

like image 707
Will I Am Avatar asked Jun 18 '15 22:06

Will I Am


2 Answers

0__'s answer is almost there. If you make the Factory[A[_,_]] a typeclass you are all set. Here is an example with the names standardised:

// 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)
}

Now test test the factory in the 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)
like image 53
iain Avatar answered Nov 20 '22 04:11

iain


The new keyword cannot be used with a type parameter, only a concrete class, because the instantiation is checked at compile time. You can work around this using reflection.

The probably better approach is to provide specific factories.

E.g.

trait Factory[A[_,_]] {
  def make[P, Q](p: P, q: Q): A[P, Q]
}

case class a[a1,a2](j:a1, k:a2) {}

object AFactory extends Factory[a] {
  def make[P, Q](p: P, q: Q): a[P, Q] = a(p, q)
}
like image 27
0__ Avatar answered Nov 20 '22 04:11

0__