从Scala中的类型参数创建对象 [英] Creating an object from a type parameter in Scala
本文介绍了从Scala中的类型参数创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个接受类型参数的方法,该方法的构造函数上显然没有任何参数,然后返回用该构造函数构造的虚拟对象.基本上是某种工厂模式.
I want to create a method that takes a type parameter, obviously with no parameters on its constructor, and returns a dummy object constructed with that constructor. Basically some kind of factory pattern.
- 在Scala中甚至有可能吗?
- 这是个好主意吗?有没有更好的模式?
- 有没有办法仅在编译时(即不进行反射)实现这一目标?
代码示例:
trait Model
class A extends Model
class B extends Model
def dummy[T <: Model] = new T // Fails compilation with "class type required but T found"
dummy[A] // Returns an instance of A
dummy[B] // Returns an instance of B
推荐答案
这可以使用 ClassManifest
s完成,该类旨在克服擦除的作用:
This can be done using ClassManifest
s, which are designed to overcome erasure:
def dummy[T <: Model : ClassManifest] = classManifest[T].erasure.newInstance
至于在编译时不进行反射,我想它可以使用scala 2.10宏来完成.
As for doing it at compile time without reflection, I guess that it could be done using scala 2.10 macros.
这篇关于从Scala中的类型参数创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文