I think I've found a bug in the UML 2.0 OCL spec.
It's actually a well-known issue for C++, documented e.g. in the
C++ FAQ.
It's not so obvious in Java, since Java didn't have Templates for a long time.
The
UML 2.0 OCL
spec says on page A-22, Definition A.27 (Type Hierarchy)
If t' ≤ t then Set(t') ≤ Set(t)
With ≤ having the meaning "conforms to" for types.
[Update:
newer UML 2.0
OCL document, the latest I could find, page 38 still says the same]
Any good C++ programmer should know that this doesn't work. From the
C++ FAQ "Is a parking-lot-of-Car a kind-of parking-lot-of-Vehicle?":
"A Bag-of-Apple is not a kind-of Bag-of-Fruit." If a Bag-of-Apple could be
passed as a Bag-of-Fruit, someone could put a Banana into the Bag, even though
it is supposed to only contain Apples!
Note that the converse, Set(t) ≤ Set(t'), also doesn't hold. While you can
put Apples into a Bag-of-Fruit just fine, you may still find a Banana in there.
This has an obvious reason: when passing data
to the object it can
be "downcasted", and when retrieving data it can be "downcasted", too. But it
can never be upcasted.
This should occur in OCL, too. A "Set(Apple)" doesn't conform to "Set(Fruit)"
by the usual interpretations that I can call "put(Banana)" on any "Set(Fruit)"!
Can anyone enlight me, if this really is a bug in the OCL spec, maybe has
already been corrected, or if there is some magic in OCLs definition of
"conforms to" or interfaces that solves this problem?
(Yes, I think there might be something in OCL that solves this problem, for
example if this hierarchy is only used in condition checking, then in fact
all operations are "get" operations... but I've just started reading on
OCL, I don't know much about its expressiveness yet...)
[Update:
Onne Gorter has
some good thoughts on this. He basically notes that this is not a problem
if you don't have any references to the "uncasted" list. For example if the
cast is a function like in a functional language that actually returns a
new set. I'll have to consider this for OCL, but given that OCL and UML are
somewhat designed for Java - and Java suffers from this problem, too - I'm
not so sure about it.]