开发者

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

开发者 https://www.devze.com 2023-02-17 04:13 出处:网络
I\'m currently learning scala. Why this code doesn\'t work: class GenClass[T](var d : T) { var 开发者_StackOverflow中文版elems: List[T] = Nil

I'm currently learning scala.

Why this code doesn't work:

class GenClass[T](var d : T) {
  var 开发者_StackOverflow中文版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?


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消