【发布时间】:2011-11-06 01:12:22
【问题描述】:
我有一个 mixin 类,它为不共享共同遗产的不同类型捆绑了功能。使用 @Mixin 注释应用混合,因此在编译时处理。
一些 mixin 方法返回 this 作为方法调用的结果。问题是 this 是混合类型而不是基类的类型。当我想在应用程序的其余部分中键入时,会抛出 ClassCastException,说明无法将混合类型强制转换为基本类型。
在下面的示例代码中,return this 返回一个 AMixin 类型的对象,而不是一个 BaseClass 类型的对象。
如何让return this 返回 BaseClass 类型的对象而不是 AMixin 类型的对象?
class AMixin {
def getWhatIWant(){
if(isWhatIwant){
return this
} else {
getChildWhatIWant()
}
}
def getChildWhatIWant(){
for (def child in childred) {
def whatIWant = child.getWhatIWant()
if (whatIWant) {
return whatIWant
}
}
return null
}
}
@Mixin(AMixin)
class BaseClass {
boolean isWhatiWant
List<baseClass> children
}
【问题讨论】: