Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Generics

In Java generics can only be typed with object types, no value types are allowed. This means, there will be only one single instance of the generated code. Java uses "type erasure", that means the code is generated with the generics parameter given as "Object" ( if a type constrain is given e.g. class C < T extends Y> it works with Y instead of Object). If the class user makes an instance of the generic, the compiler inserts cast to all references going in and out of the generics, in the places where it is used.

D templates are different of this behaviour in many ways, so TioPort takes the Java way to achieve Java behaviour. That means, TioPort will generate a normal class, and will insert all needed casts where it is used.

Arrays

Why are arrays related to generics?

In Java arrays are objects. They can be non null, but have zero length. In D there is no difference in being of length zero and of being null. A D array is a struct (value type) that contains ptr and length. Because of this fundamental difference in behaviour, TioPort need that ported code to use array-objects.

There is a D template JArrayT for an array. Aliases exist to make one dimensional arrays for all primitive data types and for JObject. If other types are used, they are handled like generics. The type information does not exist in the runtime class, type erasure is used. TioPort will insert casts where it is needed. Arrays with more dimensions are JArrayJObject instances, that hold an array of other JArrayT objects.

The instanceof problem

More tricky is the use of instanceof operator on arrays. While using it on generics, in Java compile time error is issued. This is because of the type erasure. But it is possible for arrays. If array are implemented like generics, they do not hold any element type information.

To solve this, JArrayJObject stores the classinfo of the element type. This can be used a runtime for arrayTestInstanceOf function. TioPort converts instanceof calls that test for array types, to a call to this function.