Following up on an earlier SO question, now I want to collect the Fruit
into a basket but know the sub-type on the way out.
class Banana : Fruit {
var color: string;
}
class Apple: Fruit {
var poison: bool;
}
class Fruit {
}
var a = new Apple(poison=true);
var b = new Banana(color="green");
if (a.type == Apple) {
writeln("Go away doctor!");
}
var basketDom = {1..1};
var basket: [basketDom] Fruit;
basket.push_back(a);
basket.push_back(b);
for b in basket {
writeln(b.type:string);
}
This prints the supertype Fruit
. How can I get Apples
and Bananas
out of this basket?
A quick hack (unless an actual solution to this exists) would be send a tuple into the
basket
where the tuple would represent(type_of_object, typecasted_object)
.Your code would hence become,
This will give you
Further, you can access the types using the index. eg -
b[1]
would be the type andb[2]
the object content.To access the class variables such as
poison
andcolor
after this, you could do something likeand similarily for the class
Apple
.