如何在 scala 的泛型方法中创建特征的实例?
我正在尝试使用此方法创建特征的实例,
val inst = new Object with MyTrait
这效果很好,但我想将此创建移动到生成器函数中,即。
object Creator {
def create[T] : T = new Object with T
}
显然,我需要清单来以某种方式解决类型擦除问题,但在解决这个问题之前,我遇到了两个问题:
即使有隐式清单,Scala 仍然要求 T 是一个特征。如何向 create[T] 添加限制以使 T 成为一个特征?
如果我选择使用 Class.newInstance 方法动态创建实例而不是使用“new”,我将如何在“new Object with T”中指定“with”?是否可以在运行时动态创建新的具体 mixin 类型?
I'm trying to create an instance of a trait using this method
val inst = new Object with MyTrait
This works well, but I'd like to move this creation in to a generator function, ie.
object Creator {
def create[T] : T = new Object with T
}
I'm obviously going to need the manifest to somehow fix the type erasure problems, but before I get to this, I run in to 2 questions :
Even with an implicit manifest, Scala still demands that T be a trait. How do I add a restriction to create[T] so that T is a trait?
If I chose to use the Class.newInstance method to create the instance dynamically rather than using "new", how would I specify the "with" in "new Object with T"? Is it possible to dynamically create new concrete mixin types at runtime?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定您问题的动机是什么,但您可以考虑将
T
的工厂作为隐式参数传递。这称为使用类型类或临时多态性。另一方面,您可以在运行时调用编译器,详见 这个答案“Scala 中的动态混合 - 可能吗?”。
I'm not sure what the motivation is for your question, but you could consider passing a factory for
T
as an implicit parameter. This is known as using type classes or ad-hoc polymorphism.At the other end of the spectrum, you could invoke the compiler at runtime, as detailed in this answer to the question "Dynamic mixin in Scala - is it possible?".
你不能这样做(即使有清单)。代码
new Object with T
涉及创建一个新的匿名类,表示Object与T
的组合。要将其传递给您的 create 函数,您必须在运行时生成这个新类(带有新字节码),而 Scala 没有在运行时生成新类的工具。一种策略可能是尝试将工厂方法的特殊功能转移到类的构造函数中,然后直接使用构造函数。
另一种可能的策略是为您有兴趣与此类一起使用的特征创建转换函数(隐式或其他方式)。
You can't do this (even with a Manifest). The code
new Object with T
involves creating a new anonymous class representing the combination ofObject with T
. To pass this to yourcreate
function, you would have to generate this new class (with new bytecode) at runtime, and Scala has no facilities for generating a new class at runtime.One strategy might be to try to transfer the special functionality of the factory method into the class's constructor instead, and then use the constructor directly.
Another possible strategy is to create conversion functions (implicit or otherwise) to the traits you're interested in using with this class.