有没有办法在一个函数返回语句中返回多个值(而不是返回一个对象),就像我们在Go (或其他一些语言)中所做的那样?
例如,在Go中,我们可以这样做:
func vals() (int, int) {
return 3, 7
}这可以在Dart中完成吗?如下所示:
int, String foo() {
return 42, "foobar";
} 发布于 2017-07-26 21:36:46
Dart不支持多个返回值。
你可以返回一个数组,
List foo() {
return [42, "foobar"];
}或者,如果您希望输入值,请使用像https://pub.dartlang.org/packages/tuple提供的包那样的Tuple类。
另请参阅either,了解返回值或错误的方法。
发布于 2017-11-23 01:45:16
我想补充的是,Go中多个返回值的主要用例之一是错误处理,Dart以自己的方式处理异常和失败的承诺。
当然,这还剩下一些其他用例,所以让我们看看使用显式元组时代码是什么样子的:
import 'package:tuple/tuple.dart';
Tuple2<int, String> demo() {
return new Tuple2(42, "life is good");
}
void main() {
final result = demo();
if (result.item1 > 20) {
print(result.item2);
}
}虽然不是很简洁,但它是干净和富有表现力的代码。我最喜欢它的地方是,一旦你的快速实验项目真正开始,你就开始添加功能,并且需要添加更多的结构来保持事情的顶端,它不需要太多的改变。
class FormatResult {
bool changed;
String result;
FormatResult(this.changed, this.result);
}
FormatResult powerFormatter(String text) {
bool changed = false;
String result = text;
// secret implementation magic
// ...
return new FormatResult(changed, result);
}
void main() {
String draftCode = "print('Hello World.');";
final reformatted = powerFormatter(draftCode);
if (reformatted.changed) {
// some expensive operation involving servers in the cloud.
}
}因此,是的,与Java相比,它没有太大的改进,但它在构建UI方面是有效的,它是明确的,并且相当有效。我真的很喜欢这样的方式,我可以快速地将事情组合在一起(有时在工作休息时开始使用DartPad ),然后在我知道项目将继续存在和发展的时候添加结构。
发布于 2020-07-24 02:09:52
创建一个类:
import 'dart:core';
class Tuple<T1, T2> {
final T1 item1;
final T2 item2;
Tuple({
this.item1,
this.item2,
});
factory Tuple.fromJson(Map<String, dynamic> json) {
return Tuple(
item1: json['item1'],
item2: json['item2'],
);
}
}你想怎么叫就怎么叫吧!
Tuple<double, double>(i1, i2);
or
Tuple<double, double>.fromJson(jsonData);https://stackoverflow.com/questions/45326310
复制相似问题