logoalt Hacker News

tobinfekkeslast Sunday at 10:43 PM3 repliesview on HN

Can someone smarter than me explain what they mean by "reified generics", "erased generics", and a use case for when to use one over the other?


Replies

meindnochlast Monday at 9:21 AM

With reified generics, the code

  class Foo<X> {
    X x;
  }

  Foo<int> fooInt;
  fooInt.x = 5;
  Foo<float> fooFloat;
  fooFloat.x = 5.0;
compiles to:

  class Foo_int {
    int x;
  }

  class Foo_float {
    float x;
  }

  Foo_int fooInt;
  fooInt.x = 5;
  Foo_float fooFloat;
  fooFloat.x = 5.0;

On the other hand, erased generics compiles to this:

  class Foo {
    void* x;
  }

  Foo fooInt;
  fooInt.x = new int(5);
  Foo fooFloat;
  fooFloat.x = new float(5.0);
gloryjuliolast Sunday at 10:54 PM

Example, Java is using erased generics. Once the code is compiled, the generics information is no longer in the bytecode. List<String> becomes List<>. This is called type erasure.

C# is using reified generics where this information is preserved. List<String> is still List<String> after compilation

show 2 replies
Gibbon1last Sunday at 10:57 PM

I'm not smarter than you but.

I believe the terms reified generics and erased generics is the type sweaty donkey ball terminology you get for professional CS academics.

Sticking my neck out further.

Reified generics means the type is available at run time. In C# you can write if(obj.GetType() == typeof(typename))

Erased generics the type information is not available at run time. That's the way Java does it and it kinda sucks.

show 3 replies