gpt4 book ai didi

使用 apply 方法的泛型类型的 Scala 工厂?

转载 作者:行者123 更新时间:2023-12-04 14:56:03 25 4
gpt4 key购买 nike

假设我有以下特征,它定义了一个接口(interface)并接受了几个类型参数......

trait Foo[A, B] {

// implementation details not important

}

我想将伴随对象用作特征的具体实现的工厂。我还想强制用户使用 Foo接口(interface)而不是子类化所以我将具体实现隐藏在伴随对象中,如下所示:
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似乎接近标记。

最佳答案

怎么样:

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(testing.X$Thing@4678c730)
AnotherFooImpl(testing.X$Thing@c038203)

关于使用 apply 方法的泛型类型的 Scala 工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39682752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com