1

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 to Try<MappingResult>

ElderMael
  • 7,000
  • 5
  • 34
  • 53

1 Answers1

3

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.

John Vasileff
  • 5,292
  • 2
  • 22
  • 16
  • The thing is that I do not want to return a Try because if I want to chain that to another map then the mapping function has to be MappingResult(Result|Exception) and for using it I will have to use flow typing to narrow the argument. – ElderMael Apr 01 '16 at 14:31