Creating an object from a type parameter in Scala

╄→гoц情女王★ 提交于 2021-02-16 14:54:09

问题


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.

  • Is that even possible in Scala?
  • Is that a good idea? Any better pattern if it is not?
  • Is there a way to achieve this at compile-time only (i.e. without reflection)?

Code example :

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

回答1:


This can be done using ClassManifests, which are designed to overcome erasure:

def dummy[T <: Model : ClassManifest] = classManifest[T].erasure.newInstance

As for doing it at compile time without reflection, I guess that it could be done using scala 2.10 macros.



来源:https://stackoverflow.com/questions/15861441/creating-an-object-from-a-type-parameter-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!