[英]How can I return the right data type of a instance when this instance might have different data type?
I have this code in Modula-2, 我在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;
I have several problems when I try to convert this code into java. 当我尝试将此代码转换为Java时遇到一些问题。 I can create an instance and judge if its instance is null and then choose what to return.
我可以创建一个实例并判断其实例是否为null,然后选择要返回的内容。 But I don't really know what to do with the case 2, which is the instance might be a new Opentype();
但是我真的不知道如何处理案例2,因为实例可能是一个新的Opentype();。 because only one value can be returned in this case.
因为在这种情况下只能返回一个值。
public TypeExp Prune(TypeExp typeExp){
TypeExp r = new VarType();
if (r.instance == null) {
return r;
}
else {
r.instance = Prune(r.instance);
return r.instance;
}
}
The second issue is I don't think I can call the function Prune() inside itself, so what can I do? 第二个问题是我认为自己无法调用函数Prune(),该怎么办? Thanks in advance.
提前致谢。
I dont really know Modula-2, but it might be something like this: 我不太了解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;
}
The Modula code does not return in all code paths. 并不是所有的代码路径都返回Modula代码。 Thats not possible in Java.
这在Java中是不可能的。 I inserted return null in those cases.
在这些情况下,我插入了return null。 Thats probably wrong for your application though.
那也许对您的应用是错误的。
Below example not same as your func, but I think you can modify to your needs. 下面的示例与您的func不同,但是我认为您可以根据需要进行修改。 It hides your return types behind Type class => you can return objects of two classes.
它会将您的返回类型隐藏在Type类=>后面,您可以返回两个类的对象。
Main 主要
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;
}
}
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;
}
}
FirstType 第一类
package com.type;
public class FirstType extends Type {
}
SecondType SecondType
package com.type;
public class SecondType extends Type {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.