我在锡兰有以下代码:
shared class Try<out Result> given Result satisfies Anything {
late Result|Exception computationResult;
shared new (Result() computation) {
try {
this.computationResult = computation();
} catch (Exception e) {
this.computationResult = e;
}
}
new fromResult(Result|Exception computationResult) {
this.computationResult = computationResult;
}
shared Result|Exception result() => this.computationResult;
shared Try<MappingResult> map<MappingResult>(MappingResult(Result) mappingFunction) {
if (is Result computationResult) {
try {
MappingResult mappingResult = mappingFunction(computationResult);
return Try.fromResult(mappingResult);
} catch (Exception e) {
return Try.fromResult(e);
}
} else {
return Try.fromResult(computationResult);
}
}
}
现在,当我尝试使用fromResult
这样的 Exception 实例来使用构造函数时:
} catch (Exception e) {
return Try.fromResult(e);
}
我收到以下错误:
返回的表达式必须可分配给地图的返回类型:
Try<Exception>.fromResult
不可分配给Try<MappingResult>