假設我有以下的特徵定義的接口,並需要幾個類型參數...使用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'之間的關係?遺產?沒有關係? –