When you use type constraint, it is possible to realize specialized object containers such as the one
illustrated in the example.
class Item {
public function new() {}
}
class Movie extends Item { }
class Butterly extends Item { }
class Collection < T : Item >
(continued)
126
Part I: The Core Language
{
public function new() {}
public function add(item : T)
{
// implementation goes here
}
}
In your application you can use the Collection type to create a container just for movies or butterflies.
var movies = new Collection < Movie > (); // the constraint is on the class Movie
movies.add(new Movie()); // accepted value
movies.add(new Butterly()); // compiler does not permit this
Constraints are also useful with standard types. A constraint on Float can limit the accepted values to
numbers; at instantiation it is possible to state if the value must be integer or real.
class Point < T : Float >
{
public var x : T;
public var y : T;
public function new(x : T, y : T)
{
this.x = x;
this.y = y;
}
}
The class can then be used in the following way:
var pInt = new Point < Int > (10, 20);
// pInt.
Pages:
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269