Hacker News new | ask | show | jobs
by dkharrat 3739 days ago
Type erasure introduces limitations on what you can do at runtime that forces a developer to write code to workaround it. For example, in Java you can't write a generic method that instantiates an object based on the type of the generic. The workaround is typically to pass in the Class type as an additional parameter to the method, which in theory should not be necessary. A lot of JVM-based languages are required to introduce additional complexity in the language to simulate reified generics (e.g. Scala's Manifest/TypeTag classes).
3 comments

> For example, in Java you can't write a generic method that instantiates an object based on the type of the generic. The workaround is typically to pass in the Class type as an additional parameter to the method, which in theory should not be necessary.

If a method needs to instantiate an object, the normal technique is to accept a factory function as a parameter. You can do the same thing with type-erased generics.

C# decided to create a shortcut for calling the constructor of a generic type parameter. But, for example, you can't call static methods of a generic type parameter (and a constructor is really just a slightly special static method).

> A lot of JVM-based languages are required to introduce additional complexity in the language to simulate reified generics (e.g. Scala's Manifest/TypeTag classes).

I'm not sure how this makes sense. These tags are just standard context bounds, which are extremely useful and quite awesome.

You make it sound as if these tags were some kind of special feature added to the language, or context bounds were solely invented to support these tags.

Passing in the class type for instantiating a new instance is not what you should do in your applications. You don't know at compile time if the class you pass in has a default constructor, so your program can fail at runtime. As others have stated, the right thing to do is pass in a factory object. C# solves this by adding even more cruft to the language in the form of a "new constraint" that tells the compiler to ensure that the type has a default constructor. https://msdn.microsoft.com/en-us/library/sd2w2ew5.aspx