实例化类在Scala中的通用方法 [英] Instanciate concrete class a generic method in scala

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

问题描述

我有一个通用方法,其中通用类型参数TMyClass的子类.在该方法内部,我想创建一个T的新实例,该怎么做?

I have a generic method which a generic type parameter T which is a subclass of MyClass. Inside that method, I want to create e new instance of T, how can I do that?

这不起作用(由于类型擦除):

This doesn't work (because of type erasure):

object Demo extends App {
  def myMethod[T <: MyClass](): Unit = {
      val t = new T // gives error: class type required by T found 
  }
  myMethod[MySubclassA]()
}


abstract class MyClass
class MySubclassA extends MyClass
class MySubclassB extends MyClass

推荐答案

它无法工作,但(主要是)由于类型擦除而无法工作,但是因为您的定义对于满足类型限制的所有T都是有意义的,而new T则没有.例如. T可以是MyClass或抽象子类,也可以是没有无参数构造函数的子类,也可以是特征(特征可以扩展类)或...

It fails to work, but not (primarily) because of type erasure, but because your definition should make sense for all T which satisfy the type bounds, and new T doesn't. E.g. T can be MyClass or an abstract subclass, or a subclass without a parameter-less constructor, or a trait (traits can extend classes), or...

如果运行时错误足够好,则可以采用Sergey Lagutin的解决方案.但是在大多数情况下,更合理的方法是通过某种方式将T创建为myMethod.可能作为隐式参数,例如

If a runtime error is good enough, you can go with Sergey Lagutin's solution. But more reasonable for most cases would be to pass some way to create a T to myMethod. Possibly as an implicit argument, e.g.

class Factory[T](f: () => T) {
  def make(): T = f()
}
object Factory {
  implicit val MySubclassAFactory = 
    new Factory(() => new MySubclassA) 
  implicit val MySubclassBFactory = 
    new Factory(() => new MySubclassB)
}
def myMethod[T <: MyClass](implicit factory: Factory[T]): Unit = {
  val t = factory.make()
  ...
}

myMethod[MySubclassA] // works
myMethod[MyClass] // compilation error
myMethod[ASubclassForWhichFactoryIsNotDefined] // compilation error

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

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