带有泛型的Scala工厂方法 [英] Scala factory method with generics

查看:49
本文介绍了带有泛型的Scala工厂方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个对象,我正在尝试为其编写工厂方法.

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

简化,这些是:

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

这显然行不通(出于各种原因,包括T 不能接受参数"),但是是否有一个优雅的解决方案来创建这样的东西?

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

推荐答案

0__ 的答案差不多了.如果你让 Factory[A[_,_]] 成为一个类型类,你就全部设置好了.以下是名称标准化的示例:

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

现在在 REPL 中测试工厂

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)

这篇关于带有泛型的Scala工厂方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆