我目前正在试验颤振框架和飞镖,偶然发现了一个我无法理解的看似奇怪的行为。尽管实际问题发生的环境要复杂得多,但我什至能够在一个极其简化的展示中复制它:
Stream<Either<String, int>> result1 = Stream.fromIterable([1, 2, 3, 4, 5])
.map((number) => number < 4 ? Right(1) : Left('error'))
.onErrorReturnWith((error) => Left('error'));
虽然上面的示例编译不矛盾,但我确实收到以下示例的编译错误:
错误:“Left<String, dynamic>”类型的值不能分配给“Right<dynamic, int>”类型的变量
Stream<Either<String, int>> result2 = Stream.fromIterable([1, 2, 3, 4, 5])
.map((number) => Right(1))
.onErrorReturnWith((error) => Left('error'));
有没有人能够阐明这种方式?
################################################# ######
另一个例子:
Future<Either<String, int>> someWebCall() {
Future<int> response = Future.delayed(Duration(milliseconds: 200), () {
throw SocketException('Well... ...it happens you know...');
});
return response.then((number) {
return number > 50.0 ? Right(number) : Left('number is too small...');
}).catchError((error) {
return Left('are you already questioning the meaning of your life?');
});
}
这会编译但以运行时错误结束:类型“未来”不是类型“未来<Either<String, int>>”的子类型
然后,我尝试向编译器提供尽可能多的提示,以提出这种方法:
Future<Either<String, int>> someWebCall() {
Future<int> response = Future.delayed(Duration(milliseconds: 200), () {
throw SocketException('Well... ...it happens you know...');
});
return response.then<Either<String, int>>((number) {
return number > 50.0 ? Right(number) : Left('number is too small...') as Either<String, int>;
}).catchError((error) {
return Left('are you already questioning the meaning of your life?') as Either<String, int>;
});
}
现在我得到: type 'Left<String, dynamic>' is not a subtype of type 'Either<String, int>' in type cast
我真的无法理解这个