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

2

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?

Petulant answered 17/3, 2011 at 8:33 Comment(3)
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.Cephalic
Yes - for me this solution look sufficient and simply.Petulant
possible duplicate of How to instantiate an instance of type represented by type parameter in ScalaPetulant
V
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

Virgate answered 17/3, 2011 at 8:42 Comment(0)
I
2

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

Ischium answered 17/3, 2011 at 12:7 Comment(3)
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.Cephalic
Even if you have the manifest there is not necessarily a constructor with a given signature, or any; T might be a trait!Ischium
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.Petulant

© 2022 - 2024 — McMap. All rights reserved.