Scala工厂使用Apply方法获取泛型类型? [英] Scala factory for generic types using the apply method?
本文介绍了Scala工厂使用Apply方法获取泛型类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我具有以下定义接口的特征并采用几个类型参数...
Suppose that I have the following trait that defines an interface and takes a couple of type parameters...
trait Foo[A, B] {
// implementation details not important
}
我想将伴随对象用作特征的具体实现的工厂.我还想强迫用户使用Foo
接口而不是子类,所以我将具体实现隐藏在伴随对象中,如下所示:
I want to use the companion object as a factory for concrete implementations of the trait. I also want to force users to use the Foo
interface instead of sub-classing So I hide the concrete implementations in the companion object like so:
object Foo {
def apply[A, B](thing: Thing): Foo[A, B] = {
???
}
private case class FooImpl[A1, B1](thing: Thing) extends Foo[A1, B1]
private case class AnotherFooImpl[A2, B1](thing: Thing) extends Foo[A2, B1]
}
我希望能够按如下方式使用工厂:
I want to be able to use the factory as follows:
val foo = Foo[A1, B1](thing) // should be an instance of FooImpl
val anotherFoo = Foo[A2, B1](thing) // should be an instance of AnotherFooImpl
如何实现apply
方法来实现这一目标? SO帖子似乎已接近目标.
How do I implement the apply
method to make this happen? This SO post seems close to the mark.
推荐答案
怎么样:
trait Foo[A, B]
trait Factory[A, B] {
def make(thing: Thing): Foo[A, B]
}
class Thing
object Foo {
def apply[A, B](thing: Thing)(implicit ev: Factory[A, B]) = ev.make(thing)
private case class FooImpl[A, B](thing: Thing) extends Foo[A, B]
private case class AnotherFooImpl[A, B](thing: Thing) extends Foo[A, B]
implicit val fooImplFactory: Factory[Int, String] = new Factory[Int, String] {
override def make(thing: Thing): Foo[Int, String] = new FooImpl[Int, String](thing)
}
implicit val anotherFooImplFactory: Factory[String, String] = new Factory[String, String] {
override def make(thing: Thing): Foo[String, String] = new AnotherFooImpl[String, String](thing)
}
现在:
def main(args: Array[String]): Unit = {
import Foo._
val fooImpl = Foo[Int, String](new Thing)
val anotherFooImpl = Foo[String, String](new Thing)
println(fooImpl)
println(anotherFooImpl)
}
收益:
FooImpl(testing.X$Thing@4678c730)
AnotherFooImpl(testing.X$Thing@c038203)
这篇关于Scala工厂使用Apply方法获取泛型类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文