假设我有以下的特征定义的接口,并需要几个类型参数...使用apply方法的泛型类型的Scala工厂?
trait Foo[A, B] {
// implementation details not important
}
我想使用的同伴对象的一个工厂性状的具体实现。我也想强迫用户使用Foo
接口,而不是子类所以我躲在同伴对象的具体实现,像这样:
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]
}
我希望能够使用工厂如下:
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 post似乎接近标记。
什么是'A1'和'A2'之间的关系?遗产?没有关系? –