I have the following code in Ceylon:
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);
}
}
}
Now, when I try to use the constructor fromResult
using an instance of Exception like this:
} catch (Exception e) {
return Try.fromResult(e);
}
I get the following error:
Returned expression must be assignable to return type of map:
Try<Exception>.fromResult
is not assignable toTry<MappingResult>
You can provide the type argument explicitly with <MappingResult>
, as in:
shared Try<MappingResult> map<MappingResult>(MappingResult(Result) mappingFunction) {
if (is Result computationResult) {
try {
MappingResult mappingResult = mappingFunction(computationResult);
return Try<MappingResult>.fromResult(mappingResult);
} catch (Exception e) {
return Try<MappingResult>.fromResult(e);
}
} else {
return Try<MappingResult>.fromResult(computationResult);
}
}
Note that there is an open issue to improve the error message you received - https://github.com/ceylon/ceylon/issues/6121.