Iterators

Iterators in MOF Script are used primarily for iterating collections of model elements from a source model. The forEach statement defines an iterator over a collection of something, such as a model element collection, a list/hashtable, or a String/Integer.

A forEach statement may be restricted by a type constraint (collection->forEach (c:someType)), where the type can be a metamodel type or a built-in type. If a type constraint is not given, all elements in the input collection applies. A forEach statement may also have a guard (an addition constraint), which basically is any kind of Boolean expression. A constraint is described after the type using a vertical bar symbol (‘|’) (collection->forEach (a:String | a.size() = 2)

-- applies to all objects in the collection of type Operation
c.ownedOperation->forEach(o:uml.Operation) {
       -- statements.
}

-- applies to all objects in the collection
-- of type Operation that has a name that starts with ‘a’

c.ownedOperation->forEach(o:uml.Operation | o.name.startsWith(“a”)) {
    /* statements */
}

// applies to all operation elements in the collection that // has more than zero parameters and a return type
c.ownedOperation->forEach(o:uml.Operation | o.ownedParameter.size() > 0 and o.returnResult.size() > 0) {
    /* statements */
}

 

Iterators for List and Hashtable variables

Iterators may also be defined for List/Hashtable variables, as illustrated below.

  var list1:List
  list1.add("E1")
  list1.add("E2")
  list1.add(4)
  list1->forEach(e){
    stdout.println (e)
  }

Iterators for Strings

String iterators define loops over the character contents of a string.
  var myVar: String = "Jon Oldevik"   
  myVar->forEach(c)
    stdout.print (c + " ")

Iterators for Integers

Integer iterators define loops based on the size of the context integer. E.g. integer ‘3’ will produce a loop running 3 times.

  property aNumber:Integer = 34
  aNumber->forEach(n)

       stdout.print(" " + n)
 

Iterators for String and Integer literals

Iterators can also be defined using String or Integer literals. These work the same manner as iterators based on String and Integer properties/variables.

  "MODELWare, the MDA(tm) project"->forEach(s)
       stdout.print ("" + s) 

  5->forEach(n)
       stdout.println (" " + n)