타입 인자
클래스는 범용적인 처리를 위해 사용되는 여러 타입 인자를 가질 수 있습니다. 예를 들면, Array 클래스는 하나의 타입 인자를 갖고 있습니다 :
class Array<T> { function new() { // ... } function get( pos : Int ) : T { // ... } function set( pos : Int, val : T ) : Void { // ... } }
Array 클래스 안쪽의 T는 T의 필드와 메서드에 접근이 불가능한 추상 멤버입니다. 하지만 배열 선언 시에 사용할 타입을 정할 수 있습니다 : Array<Int>나 Array<String> 처럼요. 그렇게 하면 Array 선언 안의 모든 T가 지정한 타입으로 교체됩니다.
타입 인자는 Array, List, Tree 같은 컨테이너의 엄격한 타입 검사를 처리할 때에 유용합니다. 타입 인자들은 클래스를 선언할 때에 사용하고 싶은만큼 정의할 수 있습니다.
인자 제한
While it's nice to be able to define abstract parameters, it is also possible to define several constraints on them in order to be able to use them in the class implementation. For example :
class EvtQueue<T : (Event, EventDispatcher)> { var evt : T; // ... }
In this class, although the field evt is a class paramater, the typer knows that it has both types Event and EventDispatcher so it can actually access it like if it was implementing both classes. Later, when an EvtQueue is created, the typer will check that the type parameter either extends or implements the two types Event and EventDispatcher. When multiple constraint parameters are defined for a single class parameter, as in the example above, they should be placed within parenthesis in order to disambiguate from cases where more class parameters are to follow.
Type parameter constraints are a powerful feature that lets a developer write generic code that can be reused across different applications.
«« 객체 지향 프로그래밍 - Enums »»