7.5.15 元组
可以把多个值组合为一个tuple(元组)。一个元组包含多个命名的部分,每个部分都有特定的类型。一些元组的示例如下:
Tuple {name: String='John', age: Integer=10}
Tuple {a: Collection(Integer) = Set{1, 3, 4}, b: String='foo', c: String='bar'}
OCL中也有书写元组字面量的方法;它们被包裹在大括号中,每个部分与其它部分通过逗号分隔。类型名师可选的,每个部分的次序并不重要。因此:
Tuple {name: String='John', age: Integer=10} 等同于
Tuple {name='John', age=10} 和
Tuple {age=10, name='John'}
注意,每个部分的值可以是任意的OCL表达式,因此,我们可以写:
context Person def:
statistics: Set(Tuple(company: Company, numEmployees: Integer,
wellpaidEmployees: Set(Person), totalSalary: Integer)) =
managedCompanies->collect(c |
Tuple {company: Company=c, numEmployees: Integer=c.employee->size(),
wellpaidEmployees: Set(Person)=c.Job->select(salary>10000).employee->asSet(),
totalSalary: Integer=c.Job.salary->sum()
}
)
这为某个人所管理的每个公司生成了一个元组的集合(bag),概述了公司、员工数量、高工资员工,以及工资总成本。
元组中的每个部分使用点号表示法来访问,如同属性访问一样。例如:
Tuple {x: Integer=5, y: String='hi'}.x = 5
为真。使用上面的统计定义,我们可以写:
context Person inv:
statistics->sortedBy(totalSalary)->last().wellpaidEmployees->includes(self)
该表达式断言了某人是他所管理的工资总成本最高的公司中薪水最高的员工之一。在该表达式中,‘totalSalary’和‘wellpaidEmployees’都是访问的元组中的部分。