Generics
To best explain what generics are let's start with a non-generic example
of a container class: Example
class Container extends Object {
The Container's add() method accepts any value, regardless of
its class. Imagine we were using this container to store - say -
integers, and suddenly someone was adding a string to this container: $container= new Container();
When the iteration reaches the offset containing the string object,
the program will die with a fatal error, because the string class does
not provide an intValue() method. Introducing generics
This is where generics come to help you. With generics, we can create a
"container of whatever" by using a special syntax: $container= create('Container<lang.types.Integer>()');
Read this as Create a Container of Integer s. class Container extends Object { ...and then revisit the sourcecode example from above, we will see the
following behaviour: $container= create('new Container<lang.types.Integer>()');
Comparing to Java / C#
The first and most noticeable difference is the syntax they are declared
and used in. While in Java and C#, the language itself supports generics,
the XP framework needs to simulate them on top of PHP5. Because the XP
framework is written purely in PHP and because userland PHP cannot modify
the language grammar nor the way the engine works, the syntax is a bit
kludgy. Java/C# syntax is as follows: class Container<T> { The second most obvious difference is that in the XP framework, all type
checks occur at runtime, whereas Java and C# catch type errors when
compiling: $c->add(new String('Hello')); // XP: Throws an IllegalArgumentException!
Classes supporting generics
All the classes from the util.collections package
support generics:
Further reading
rfc://106 contains more information about how generics work
in the XP framework. An introduction into Java generics is availabe
here and
for C# they're explained over at MSDN. | Table of contents |