Dart lambda/shortland 函数混淆 [英] Dart lambda/shortland function confusion

查看:25
本文介绍了Dart lambda/shortland 函数混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Dart 还是很陌生,=>(粗箭头)的语法仍然让我感到困惑(我来自 C# 背景).

I'm still pretty new to Dart and the syntax of => (fat arrow) still confuses me (I come from C# background).

所以在 C# 中粗箭头 ( => ) 表示: goes to 所以例如:

So in C# fat arrow ( => ) says: goes to so for example:

Action<string> action1 = (str) => { System.Diagnostic.Debug.WriteLine("Parameter received: " + str.ToString()); }

action1("Some parameter");

意味着:任何作为参数发送到 action1(如果它可以被转换为 string)进入 内部范围(在我们的例子中它刚刚打印在 Debug.WriteLine()

means: whatever send as parameter to action1 (if it could be casted to string) goes to inner scope (in our case it just printed in Debug.WriteLine()

但在 Dart 中,情况有所不同.... (?)

but in Dart it's something different.... (?)

例如在Future.then

ClassWithFutures myClass = new ClassWithFutures();
myClass.loadedFuture.then( 
   (str) => { print("Class was loaded with info: $str"),
   onError: (exp) => { print("Error occurred in class loading. Error is: $exp"); }
);

Dart 编辑器警告我,第一个和第二个 print 是:预期的地图条目键的字符串文字.我认为在 C# 中 str 它只是参数的名称,该参数将由 Future.then 用于调用 onValue 或 <代码>onError

Dart editor warn me that the first and second print is: Expected string literal for map entry key. I think in C# way that str it just name for parameter that will be filled by internal callback that Future.then uses to call onValue or onError

我做错了什么?

推荐答案

您需要选择块语法或单表达式语法,但不能同时选择.

You need to choose either block syntax or single expression syntax, but not both.

您不能将 => 与 {}

You can't combine => with {}

使用您的示例,您的两个选项如下:

Your two options are as follows using your example:

ClassWithFutures myClass = new ClassWithFutures();
myClass.loadedFuture.then( 
  (str) => print("Class was loaded with info: $str"),
  onErrro: (exp) => print("Error occurred in class loading. Error is: $exp")
);

ClassWithFutures myClass = new ClassWithFutures();
myClass.loadedFuture.then( 
  (str) { print("Class was loaded with info: $str"); },
  onErrro: (exp) { print("Error occurred in class loading. Error is: $exp"); }
);

在这两种情况下,它只是一种表达匿名函数的方式.

In both cases, it is just a way to express an anonymous function.

通常,如果您只想运行单个表达式,您可以使用 => 语法来使代码更清晰、更准确.示例:

Normally if you want to just run a single expression, you use the => syntax for cleaner and more to the point code. Example:

someFunction.then( (String str) => print(str) );

或者您可以使用带花括号的块语法来完成更多工作,或者使用单个表达式.

or you can use a block syntax with curly braces to do more work, or a single expression.

someFunction.then( (String str) {
  str = str + "Hello World";
  print(str);
});

但是你不能将它们组合起来,因为你正在制作 2 个函数创建语法并且它中断了.

but you can't combine them since then you are making 2 function creation syntaxes and it breaks.

希望这会有所帮助.

这篇关于Dart lambda/shortland 函数混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆