5

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?

Robert Zaremba
  • 6,780
  • 6
  • 40
  • 71
  • 2
    Yup. It's a restriction from the Java roots. I usually use a "constructor function" (passed as ctor argument, for example), e.g. `() => T`, but there may be some way more nifty ways. –  Mar 17 '11 at 08:35
  • Yes - for me this solution look sufficient and simply. – Robert Zaremba Mar 17 '11 at 14:25
  • possible duplicate of [How to instantiate an instance of type represented by type parameter in Scala](http://stackoverflow.com/questions/1305563/how-to-instantiate-an-instance-of-type-represented-by-type-parameter-in-scala) – Robert Zaremba Nov 09 '11 at 20:08

2 Answers2

5

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

Community
  • 1
  • 1
Rommudoh
  • 1,834
  • 10
  • 11
2

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

Raphael
  • 6,604
  • 2
  • 48
  • 77
  • That too +1. But in the general case there is know way of knowing *what* the run-time type of T is. Scala 2.8 introduces a "general" Manifest solution for this part of the problem. –  Mar 17 '11 at 16:21
  • Even if you have the manifest there is not necessarily a constructor with a given signature, or any; `T` might be a trait! – Raphael Mar 17 '11 at 17:49
  • Yes - but the idea behind generic programming is to not solve everything (eg: type consistency). For example in C++ we can simply do everything with templates. – Robert Zaremba Mar 17 '11 at 21:17