Scala Generic,通过变量指定泛型

标签 scala generics

我有一个采用泛型的类:

class MyClass[T <: RecordType] (myRecordType: T) {
  def doAction() : Unit =
  {
    myRecordType.someMethod();
  }
}

我有一系列 RecordType 的子类,它们都实现了 someMethod()。目前,我在我的主类中分别称呼每个人如下:

def main(args: Array[String]): Unit = 
{
   new MyClass[RecordType10](new RecordType10()).doAction();
   new MyClass[RecordType20](new RecordType20()).doAction();
   new MyClass[RecordType30](new RecordType30()).doAction();
   // many more record types each repeated
}

理想情况下,我们不希望为每种记录类型添加一个新行,而是希望枚举有效的记录类型并循环遍历。这样,添加新记录类型就像添加到预定义列表一样简单。但是我无法弄清楚如何拥有类类型的数组或枚举,然后将它们传递给 MyClass 的实例化。例如,这个简单的测试:

val testClass = classOf(RecordType10);
new MyClass[testClass](new testClass()).doAction();

...它不编译。

所以基本问题是:有没有一种方法可以拥有一个类集合,然后遍历该集合并实例化另一个传递泛型类型值的类。像这样:

val myClasses = Array(classOf(Record10), classOf(Record20), classOf(Record30));
for (theClass <- myClasses)
{
   new MyClass[theClass](new theClass()).doAction();
}

期待任何回应。谢谢!

最佳答案

为简单起见,使用 OP 的示例:

object Main {
  trait RecordType {
    def someMethod()
  }

  class MyClass[T <: RecordType](myRecordType: T) {
    def doAction(): Unit = myRecordType.someMethod()
  }

  class RecordType10() extends RecordType {
    override def someMethod(): Unit = println("some method 10")
  }

  class RecordType20() extends RecordType {
    override def someMethod(): Unit = println("some method 20")
  }

  def main(args: Array[String]): Unit = {
    new MyClass[RecordType10](new RecordType10()).doAction()
    new MyClass[RecordType20](new RecordType20()).doAction()

    val myClasses = List(classOf[RecordType10], classOf[RecordType20])
    for(theClass <- myClasses) {
      val instance = theClass.newInstance()
      val m = new MyClass(instance)
      m.doAction()
    }
  }
}

关于Scala Generic,通过变量指定泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39249748/

相关文章:

c# - 泛型传递类型成员以对泛型集合进行操作

java - 使用 Akka 微内核有哪些常见用例?

Scala: "In-place"没有 "new"关键字继承的特质

scala - 在 LWJGL 3.1.4 中使用 stackPush() 时遇到问题 - NoSuchMethodError

Scala:由嵌套类型值参数化的类型级编程

Java泛型使用错误

c++ - 为什么 C++ 不使用 Java 之类的泛型类型删除?

c# - 如何返回通用 T.ToString()

json - Map[Locale, String] 的 Scala Play Json 格式

c++模板方法语法问题