如何在Scala的通用方法中创建特征的实例? [英] How do I create an instance of a trait in a generic method in scala?

查看:61
本文介绍了如何在Scala的通用方法中创建特征的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此方法创建特征的实例

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 :

  1. 即使使用了隐式清单,Scala仍然要求T为特征.如何为create [T]添加限制,以使T为特征?

  1. 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?

如果我选择使用Class.newInstance方法动态创建实例而不是使用"new",那么如何在带有T的新对象"中指定"with"?是否可以在运行时动态创建新的具体混入类型?

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?

推荐答案

您无法做到这一点(即使使用清单).代码new Object with T涉及创建代表Object with 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 of Object with T. To pass this to your create 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.

这篇关于如何在Scala的通用方法中创建特征的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆