2016-09-25 93 views
2

假设我有以下的特征定义的接口,并需要几个类型参数...使用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似乎接近标记。

+0

什么是'A1'和'A2'之间的关系?遗产?没有关系? –

回答

0

使用TypeTags(为了克服类型参数的擦除),我们可以根据传入apply方法的类型参数调用相应的隐藏实现,如下所示。它正确地实例化相应的实施方案,而是为Foo类型信息丢失,实际上它的未来的一些垃圾一样_202等?我不知道为什么会发生这种情况,以及如何保留Foo的正确类型。也许有人可以抛开这一点。

trait Foo[A,B] 
object Foo { 
    def apply[A: TypeTag, B: TypeTag](thing: Thing) = 
    if(typeTag[A] == typeTag[Int]) 
     FooImpl(thing) 
    else if(typeTag[A] == typeTag[String]) 
     AnotherFooImpl(thing) 
    else 
     new Foo[Double,Double] {} 

    private case class FooImpl(thing: Thing) extends Foo[Int, String] 
    private case class AnotherFooImpl(thing: Thing) extends Foo[String, String] 
    } 

Foo[Int,String](new Thing) // Foo[_202, _203] = FooImpl([email protected]) 

The actual types for _203 and _203 are: ??? 
// type _203 >: String with _201, type _202 >: Int with _200 


Foo[String,String](new Thing) //Foo[_202, _203] = AnotherFooImpl([email protected]) 
3

如何:

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([email protected]) 
AnotherFooImpl([email protected]) 
+0

很酷!你在使用类型参数:FooImpl [A1,B1] AnotherFooImpl [A2,B1]有什么原因?他们可能是真的吗?为前:可能只是FooImpl [A,B] AnotherFooImpl [A,B] – Samar

+1

@Samar我已经修复了,谢谢你让我通知。他们只是为了测试和玩耍。它们通常是'A'和'B',它们不受任何类型的约束。 –