[英]How can I return the right data type of a instance when this instance might have different data type?
我在Modula-2中有这段代码,
PROCEDURE Prune(typeExp: TypeExp): TypeExp;
BEGIN
CASE typeExp.^class OF
| VarType:
IF typeExp^.instance = NIL THEN
RETURN typeExp;
ELSE
typeExp^.instance = Prune(typeExp^.instance);
RETURN typeExp^.instance;
END;
| OperType: RETURN typeExp;
END;
END Prune;
当我尝试将此代码转换为Java时遇到一些问题。 我可以创建一个实例并判断其实例是否为null,然后选择要返回的内容。 但是我真的不知道如何处理案例2,因为实例可能是一个新的Opentype();。 因为在这种情况下只能返回一个值。
public TypeExp Prune(TypeExp typeExp){
TypeExp r = new VarType();
if (r.instance == null) {
return r;
}
else {
r.instance = Prune(r.instance);
return r.instance;
}
}
第二个问题是我认为自己无法调用函数Prune(),该怎么办? 提前致谢。
我不太了解Modula-2,但可能是这样的:
public TypeExp Prune(TypeExp typeExp) {
if (typeExp instanceof VarType) {
if (typeExp.instance == null) {
return typeExp;
}
else {
typeExp.instance = Prune(typeExp.instance);
return typeExp.instance;
}
} else if (typeExp instanceof OperType) {
return typeExp;
}
//if typeExp is not an instance of VarType or OperType
return null;
}
并不是所有的代码路径都返回Modula代码。 这在Java中是不可能的。 在这些情况下,我插入了return null。 那也许对您的应用是错误的。
下面的示例与您的func不同,但是我认为您可以根据需要进行修改。 它会将您的返回类型隐藏在Type类=>后面,您可以返回两个类的对象。
主要
package com.type;
public class Main {
public static void main(String[] args) {
Type first = new FirstType();
Type second = new SecondType();
System.out.println(func(first).getTypeName());
System.out.println(func(first).getTypeName());
System.out.println(func(second).getTypeName());
}
public static Type func(Type type) {
if(type instanceof FirstType) {
type.setTypeName("First");
} else {
type.setTypeName("Second");
// something here
}
return type;
}
}
类型
package com.type;
public class Type {
private String typeName;
public Type() {}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
第一类
package com.type;
public class FirstType extends Type {
}
SecondType
package com.type;
public class SecondType extends Type {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.