Generics
suggest changeSyntax
- The generic types declared within the triangle brackets:
<T>
- Constrainting the generic types is done with the extends keyword:
<T extends Car>
Remarks
The generic parameters are not available at runtime, they are just for the compile time. This means you can’t do something like this:
class Executor<T, U> {
public execute(executable: T): void {
if (T instanceof Executable1) { // Compilation error
...
} else if (U instanceof Executable2){ // Compilation error
...
}
}
}
However, class information is still preserved, so you can still test for the type of a variable as you have always been able to:
class Executor<T, U> {
public execute(executable: T): void {
if (executable instanceof Executable1) {
...
} else if (executable instanceof Executable2){
...
} // But in this method, since there is no parameter of type `U` it is non-sensical to ask about U's "type"
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents