Dart lambda/shortland function confusion

后端 未结 3 1691
时光取名叫无心
时光取名叫无心 2020-12-30 18:32

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

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

相关标签:
3条回答
  • 2020-12-30 19:14

    That syntax works well in a language like javascript and also c# where it supports (param1, param2, …, paramN) => { statements } with statement being separated with semi colon. In dart, the fat arrow only supports expression which is shorthand for { return expr; }.
    That explains your Error. Your code with the curly brace (exp) => { print("Error occurred in class loading. Error is: $exp"); } means you are returning a map, so it expects to see something like (param) => {"key": "value"} where key is a string literal.

    0 讨论(0)
  • 2020-12-30 19:18

    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")
    );
    

    or

    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);
    });
    

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

    Hope this helps.

    0 讨论(0)
  • 2020-12-30 19:18

    In Dart => xxx is just a syntaxic sugar to avoid { return xxx; }. Thus the two following functions are equivalent :

    var a = (String s) => s;
    var b = (String s) { return s; } ;
    

    You can also use => on method definitions :

    String myFunc(String s) => s;
    String myFunc(String s) {
      return s;
    }
    
    0 讨论(0)
提交回复
热议问题