How to maintain sub-type of an object in a Chapel array

84 Views Asked by At

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?

1

There are 1 best solutions below

1
On BEST ANSWER

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,

var basketDom = {1..1};
var basket: [basketDom] (string, Fruit);
basket.push_back((a.type:string, a));
basket.push_back((b.type:string, b));

for b in basket {
  writeln(b);
}

This will give you

(Apple, {poison = true})
(Banana, {color = green})

Further, you can access the types using the index. eg - b[1] would be the type and b[2] the object content.

To access the class variables such as poison and color after this, you could do something like

if (b[1] == "Banana") {
    var obj = b[2]: Banana;
    writeln(obj.color);
}

and similarily for the class Apple.