Skip to content
Dima Kruk edited this page Jan 25, 2013 · 5 revisions

Generics is a language extension that adds an generic type support to ActionScript3.

Generic type is a type that can be declared on instance creation. Unfortunately, the pure ActionScript3 supports this behavior only with Vectors. Generics language extension allows to use this behavior with any other ActionScript class. Generics using is aimed to maximize code reusing, type safety and performance.

##Declaration ###generics declaration Generics class declaration can be created right after importing the generics language extension. First, a class with one or more formal type parameters (enumerated in angle brackets) is declared. Second, these type parameters are replaced by type arguments when the class is instantiated.

public class GenericsList<T, T2, T3> { // "T" stands for "Type" here
  ...
} 
  new GenericsList.<int, int, int>(); // type arguments

Type declaration can be specialized with extends expression. Note that when we introduce T extends Sprite to the previous example, type system will report an error on the new GenericsList.<int, int, int>(), because int cannot be a child of a Sprite.

public class GenericsList<T extends Sprite, T2, T3> { // a small update: "T extends Sprite"
  ...
}
new GenericsList.<int, int, int>(); // error
new GenericsList.<Sprite, int, int>(); // valid code

##Using

###type safety

Generic types can be used as a type parameters anywhere inside the generics class. When you create a method of a generic class, any of its type parameters can be set as a type of an argument in this method. This enables type system checks and autocompletions in the IDE: when you call this method, the editor will report any type mismatching.

public class GenericsList<T, T2, T3> { // T, T2 and T3  can be used as a type anywhere inside this class
  public function GenericsList() {
    
  }

  public function myMethod(t : T) : void { // T can be set as a type of an argument
    
  } 
}
var myList : GenericsList.<int, int, int> = new GenericsList.<int, int, int>(); 
myList.myMethod(123); // valid code 
myList.myMethod("blah-blah"); // type system reports an error here

##Static Generics Type

Unlike Java, this language extension does not support static generics types.

Clone this wiki locally