我有一个工厂对象,它定义了一个 apply 方法来创建新实例:
object Key {
def apply(name: String) = new Key(name)
}
class Key(name: String)
如何让 Key
的子类以通用方式重用工厂对象,这样我就不需要为每个子类创建工厂对象?
基本上就像:
object Key {
def apply(name: String) = new [Some subclass of Key]()
}
class TypeKey(name: String) extends Key(name)
val tk = TypeKey("typeKey")
最佳答案
你不能。那么,对于这个特定的应用程序,您可以使用case class
。否则,您必须创建一个工厂对象,尽管 apply
可以在特征中实现:
trait KeyFactory[T: ClassTag] {
val constructor = classTag[T].runtimeClass.getConstructor(classOf[String])
def apply(name: String) =
constructor.newInstance(name)
}
class TypeKey(name: String) extends Key(name)
object TypeKey extends KeyFactory[TypeKey]
请注意,如果没有合适的构造函数,这将在运行时失败。
关于scala - 继承Scala中的apply方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34127083/