oclAsType lets you treat an object as a specified subtype in an OCL expression so that you can access operations defined on that subtype.
Syntax
oclAsType(typespec : Class) : T
Call oclAsType on an object and provide the class that you want the expression to be statically typed as.
What it does
oclAsType returns self with the static type specified by typespec, provided that the object is an instance of that type. It does not change the runtime value or runtime type of self.
Use it in a model with inheritance when the expression is currently typed as a base class but you need to access an attribute, association, or operation available on a subtype.
Static type and runtime type
The static type is the type OCL uses when it determines which members you can reference in the expression. The runtime type is the actual type of the object while the expression runs.
For example, assume Animal is a base class and Dog is a subclass with the attribute Breed. An expression typed as Animal cannot use Breed until it is statically typed as Dog:
self.oclAsType(Dog).Breed
The object remains the same object. oclAsType(Dog) does not convert an Animal into a Dog; it makes the subtype members available to the expression.
Check the type before casting
Before you use a subtype-specific member, test whether the object is the required type or one of its subtypes with oclIsKindOf. Then use oclAsType in the branch where the test succeeds.
- Test the object's runtime type.
- Cast the object to the subtype in the expression that needs subtype members.
- Access the subtype member.
Example:
if self.oclIsKindOf(Dog) then
self.oclAsType(Dog).Breed
else
'Not a dog'
endif
In this example, oclIsKindOf(Dog) also accepts instances of subclasses of Dog. Use the type test to express the condition; use oclAsType to gain access to the subtype's operations after that condition is met.
When to use it
| Need | Use |
|---|---|
| Test whether an object is a class or one of its subclasses | oclIsKindOf |
| Access members that belong to a subtype when the current expression has a base-class type | oclAsType
|
| Work with all currently existing instances of a classifier | allInstances |
