Typedefs?
Table of Contents
Concurnas provides a convenient mechanism for referring to type definitions. This is particularly useful for long qualified generic types. Typedefs can be used anywhere one would normally use a type. They enable us to translate the following, very verbose code:
ArrayList<Set<HashMap<ArrayList<String>, Set<int>>>> myDataStructureInstance = new ArrayList<Set<HashMap<ArrayList<String>, Set<int>>>>(10)
Into the following, far easier to read (but functionally identical) form:
typedef DataStructure = ArrayList<Set<HashMap<ArrayList<String>, Set<Integer>>>>
myDataStructureInstance DataStructure = new DataStructure(10)
This greatly improves the readability of code as well as increasing code reuse and reducing errors since less code needs to be written.
Typedefs go beyond traditional macro or type macro offerings seen in earlier languages in providing quantifiable type defs, this is particularly useful when defining typedefs on generic types where we wish to defer the generic type qualification. The syntax should feel familiar to that for using generic types:
typedef MyHashMap<X, Y> = HashMap<X, Y>
ml = new MyHashMap<int, String>()
Typedefs may refer to other typedefs like so:
typedef MyList<X> = ArrayList<X>
typedef StringList = MyList<String>
Typedefs may also refer to other typedefs during qualification of generic types:
typedef MyHashMap<X, Y> = HashMap<X, Y>
typedef MyList<X> = ArrayList<X>
item = MyList<MyHashMap<int, String>>()
Default typedefs?
A typedef may be qualified with a default type. This default type overrides the typedef's type when it's used in order to create a new instance object (e.g. via the new
keyword). This is a useful feature for instances where one wishes to make use of a typedef to create concrete instances objects, but also use the typedef in order to encompass a more broad array of types than the default type, say an abstract class, trait or interface (e.g. List<X>
vs ArrayList<X>
). Consider the following:
from java.util import List, ArrayList
typedef li<X> = List<X> default ArrayList<X>
Above, the li<X>
typedef is qualified with a default type of ArrayList<X>
. Hence, new instance objects created which refer to the li<X>
typedef will be created as instances of ArrayList<X>
, e.g.:
inst li<X> = new li<String>()
Now, inst
is a ArrayList<String>
instance object which itself is compatible with the type of inst
- the li<X>
typedef since this resolves to List<String>
which is a superclass of ArrayList<String>
.