[英]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.