使用 Ceylon 在命名构造函数中指定泛型类型

Specify Generic Type In Named Constructor With Ceylon

我在 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);
        }
    }
}

现在,当我尝试使用构造函数 fromResult 使用异常实例时,如下所示:

} catch (Exception e) {
    return Try.fromResult(e);
}

我收到以下错误:

Returned expression must be assignable to return type of map: Try<Exception>.fromResult is not assignable to Try<MappingResult>

您可以使用 <MappingResult> 显式提供类型参数,如:

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);
    }
}

请注意,有一个未解决的问题可以改进您收到的错误消息 - https://github.com/ceylon/ceylon/issues/6121