Scala factory for generic types using the apply method?

前端 未结 2 1917
春和景丽
春和景丽 2021-02-06 10:36

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 i         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-06 11:25

    How about:

    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)
    }
    

    And now:

    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)
    }
    

    Yields:

    FooImpl(testing.X$Thing@4678c730)
    AnotherFooImpl(testing.X$Thing@c038203)
    

提交回复
热议问题