How to check subclass in Chapel

跟風遠走 提交于 2020-01-01 19:14:34

问题


This one is probably really stupid. How do you check the subclass of an object in Chapel?

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");

// ?, kinda Java-ish, what should I do?
if (type(a) == Apple.class()) {
  writeln("Go away doctor!");
}

Though I'm asking about a subclass, I realize I don't know how to check if it's a Fruit class either.


回答1:


For an exact type match, you will want to write this:

 if (a.type == Apple) {
   writeln("Go away doctor!");
 }

To check if the type of a is a subtype of Fruit, this will work:

if (isSubtype(a.type, Fruit)) {
   writeln("Apples are fruit!");
}

For reference, there's a list of functions that can similarly be used to check type information here

*Note that the parentheses in the if blocks are not necessary, so you could write this instead:

if isSubtype(a.type, Fruit) {
   writeln("Apples are fruit!");
}



回答2:


The earlier answer does a fine job of explaining the case in which the type is known at compile time, but what if it's only known at run-time?

class Banana : Fruit {
  var color: string;
}
class Apple: Fruit {
  var poison: bool;
}
class Fruit {
}

var a:Fruit = new Apple(poison=true);
var b:Fruit = new Banana(color="green");

// Is a an Apple?
if a:Apple != nil {
  writeln("Go away doctor!");
}

In this case the dynamic cast of a to its potential subtype Apple results in nil if it wasn't in fact an Apple or an expression with compile-time type Apple if it was.



来源:https://stackoverflow.com/questions/45943288/how-to-check-subclass-in-chapel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!