从函数返回多个值

Ale*_*ard 24 return function dart

有没有办法在函数return语句中返回多个值(除了返回一个对象),就像我们可以在Go(或其他一些语言)中做的那样?

例如,在Go中我们可以做到:

func vals() (int, int) {
    return 3, 7
}
Run Code Online (Sandbox Code Playgroud)

这可以在Dart完成吗?像这样的东西:

int, String foo() {
    return 42, "foobar";
} 
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 30

Dart不支持多个返回值.

你可以返回一个数组,

List foo() {
  return [42, "foobar"];
}
Run Code Online (Sandbox Code Playgroud)

或者如果你想要键入值,请使用Tuplehttps://pub.dartlang.org/packages/tuple提供的类这样的类.

另请参阅either返回值或错误的方法.

  • +1 表示 `tuple`,它最接近 Go 内置的功能。它只是没有内置到 Dart 中,大概还没有太多需要,而且它们尽可能地保持语言的简洁。 (4认同)
  • 将返回类型更改为 `List<dynamic>` 或 `List<Object>` (4认同)
  • 另外*任一个*都是dart 2.0 **不兼容**。 (2认同)

Rob*_*ill 12

我想补充一点,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);
  }
}
Run Code Online (Sandbox Code Playgroud)

不那么简洁,但它是干净且富有表现力的代码。我最喜欢它的一点是,一旦您的快速实验项目真正起飞并且您开始添加功能并需要添加更多结构以保持领先地位,它就不需要改变太多。

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.
  }
}
Run Code Online (Sandbox Code Playgroud)

所以,是的,它比 Java 没有太大的改进,但是它可以工作,很清楚,并且对于构建 UI 来说相当有效。而且我真的很喜欢我如何快速地将事情组合在一起(有时在工作休息时从 DartPad 开始),然后在我知道该项目将继续存在和发展时添加结构。


Edi*_*Edi 8

创建一个类:

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'],
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

随心所欲地称呼它!

Tuple<double, double>(i1, i2);
or
Tuple<double, double>.fromJson(jsonData);
Run Code Online (Sandbox Code Playgroud)


Jua*_*cia 7

您可以创建一个类来返回多个值 Ej:

class NewClass {
  final int number;
  final String text;

  NewClass(this.number, this.text);
}
Run Code Online (Sandbox Code Playgroud)

生成值的函数:

 NewClass buildValues() {
        return NewClass(42, 'foobar');
      }
Run Code Online (Sandbox Code Playgroud)

打印:

void printValues() {
    print('${this.buildValues().number} ${this.buildValues().text}');
    // 42 foobar
  }
Run Code Online (Sandbox Code Playgroud)