Scala generics - why I can't create parametrised object inside generic class?

跟風遠走 提交于 2019-12-07 06:36:53

问题


I'm currently learning scala.
Why this code doesn't work:

class GenClass[T](var d : T) {
  var elems: List[T] = Nil 
  def dosom(x: T) = { 
    var y = new T() 
    y   
  }
}

I get: error: class type required but T found
in place of var y - new T()

Is it because type erasing from java? Is there any way to solve this - create variable of type T inside generic function?


回答1:


have a look at this question, there's an example of a factory: How to instantiate an instance of type represented by type parameter in Scala




回答2:


Because you can not be sure there always is a public, parameterless constructor.



来源:https://stackoverflow.com/questions/5336648/scala-generics-why-i-cant-create-parametrised-object-inside-generic-class

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