Dart 现已支持结构化数据

发表时间: 2023-08-05 02:39

Dart 增加了对结构化数据的支持,使用代数数据类型实现了更具功能性的风格。下面的代码显示了在函数上使用多个返回值的示例

(double x, double y) getLocation(String name) {  if (name == 'Aarhus') {    return (16.1629, 142039);  } else {    ...  }}

然后使用方法如下

void main(List<String> arguments) {  final (lat, long) = getLocation('Aarhus');  print('Current location: $lat, $long');}

还可以定义类的层次结构,然后对这些类进行模式匹配

sealed class Shape {  double calculateArea();}class Square implements Shape {  final double length;  Square(this.length);  double calculateArea() => length * length;}class Circle implements Shape {  final  double  radius;  Circle(this.radius);  double calculateArea() => radius * 2;}

然后

double calculateArea(Shape shape) => switch (shape) {  Square(length: var l) => l * l,  Circle(radius: var r) => math.pi * r * r};void main() {  double result = calculateArea(Circle(2));  print("结果1->$result");   double result2 = calculateArea(Square(2));  print("结果2->$result2");}

测试效果


传统的写法

double calculateArea2(Shape shape) {  switch (shape) {    case Square(length: var x):      print("执行-1-");      return x * x;    case Circle(radius: var r):       print("执行-2-");      return 3.14 * r * r;    default:      return 0;  }}

#头条创作挑战赛#