2.10.  Genericity

[Warning]Text not verified for kermeta 2

One of the core characteristics of Kermeta is to be statically typed. In order to allow static typing of OCL-like expressions, a few modifications had to be made to the EMOF type system (Please refer to paper Weaving Executability into Object-Oriented Meta-Languages by P.A. Muller et al., presented at the Models05 conference).

As a result to these modifications genericity support has been added into Kermeta. Like Eiffel and Java 5, Kermeta supports generic classes and generic operations. This section gives on overview of these concepts in Kermeta.

2.10.1. Generic classes

In Kermeta classes can have a set of type parameters. These type variables can be used in the implementation of the class as any other type. By default a type variable can take as value any type; but a type variable can also be constrained by a type: in that case, this type variable can only be substituted by a sub-type of this type. The following code demonstrates how to create generic classes.

// A class with a type variable G that can be bound with any type
class Queue<G>
{
     reference elements : oset G[*]

     operation enqueue(e : G) : Void is do 
         elements.add(e)
     end
     
     operation dequeue() : G is do
         result := elements.first
         elements.removeAt(0)
     end
}
// A class with a type variable C that can be bound with any sub-type of Comparable
class SortedQueue<C : Comparable> inherits Queue<C> 
{
     method enqueue(e : C) : Void is do
         var i : Integer
         from i := 0
         until i == elements.size or e > elements.elementAt(i)
         loop
             i := i + 1
         end
         elements.addAt(i, e)
     end
}

2.10.2. Generic operations

Kermeta operations can contain type parameters. Like type variables for classes these type parameters can be constrained by a super type. However, unlike for classes, for which the bindings to these type parameters are explicit, for operations the actual type to bind to the variable is statically inferred for each call according to the type of the actual parameters.

class Utils {
    operation max<T : Comparable>(a : T, b : T) : T is do
        result := if a > b then a else b end
    end
}
[Note]Note

Notice in that sample that even the "if" is an expression that can return a value that is assigned here to the special variable "result".

2.10.3. Type usable with genericity

Actually, all types can be used as a parameter of a generic class or generic operation. More, the ModelType, is really useful when combined with generics. see Section 2.23, “Model type”