在 scala 中创建类型的新实例
如果我定义了一个类 C,
class C[A]
有什么方法可以在 C 中创建 A
的新实例吗?就像
class C[A] {
def f(): A = new A()
}
我理解的那样,如果这是可能的,您可能必须在某处指定构造函数参数,这很好。
如果不可能,是否有任何设计模式可以处理您想要创建类型的新实例的情况?
If I have a class C defined as
class C[A]
is there any way to create a new instance of A
within C? Something like
class C[A] {
def f(): A = new A()
}
I understand that, if this were possible, you'd probably have to specify the constructor arguments somewhere, and that's fine.
If it's not possible, are there any design patterns for dealing with the sort of situation where you'd like to create a new instance of a type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以要求一个隐式参数,如下所示:
当您实例化
A
时,您所需要的只是在范围内拥有所需类型的隐式工厂,例如以下工作:如图所示:
You can demand an implicit parameter, like so:
All you need then is to have an implicit factory of the desired type in scope when you instanciate
A
, e.g. the following works:As shown by:
与 @Raphael 对案例类的
apply
方法的回答相同:The same as @Raphael's answer with a case class's
apply
method:您可以使用类型类来抽象实例化:
例如,
当您实例化 C 时,您需要显式或隐式地提供一个 Makeable 来充当适当类型的工厂。当然,该工厂将负责在调用构造函数时提供任何构造函数参数。
或者,您可以使用 Manifest,但请注意,此方法依赖于反射并且类型不安全:
为了完整性,您还可以轻松扩展此方法以将部分或全部构造函数参数传递到 make 方法:
You could use a type class to abstract instantiation:
For example,
When you instantiate C, you'll need to provide, explicitly or implicitly, a Makeable that will act as a factory of the appropriate type. That factory, of course, would be responsible for supplying any constructor arguments when it invokes the constructor.
Alternatively, you could use a Manifest, but be warned that this approach relies on reflection and is not type safe:
For completeness, you can also easily extend this approach to pass some or all of the constructor parameters in to the make method: