【发布时间】:2016-09-25 14:51:10
【问题描述】:
假设我有以下 trait,它定义了一个接口并接受了几个类型参数...
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是什么关系?遗产?没有关系?