dwyl / learn-dart

🎯Learn the Dart programming language to build cross-platform (Mobile, Web & Desktop) Apps with Flutter!
GNU General Public License v2.0
32 stars 8 forks source link

The cascade operator .. #7

Open SimonLab opened 4 years ago

SimonLab commented 4 years ago

In Elixir we are use to apply multiple functions on a value with the pipe operator |>

"Hello there" 
|> String.upcase() 
|> String.split()

The pipe operator takes the returned value of the function and apply the next function. This works nicely because of Elixir values are immutable and functions return a new value with the updated change from the functions.

Dart is object oriented. This means that the following doesn't work:

var l = [1,2,3];
l.add(4).add(5);

Here l is an list and the add function change the state of the list directly, it doesn't create a new list value. Moreover the add function as the following declaration:

void add(E value) 

So add returns a void value and not the list itself.

One solution to add multiple values in a list could be:

void main(){
  var a = [1,2,3];  
  a.add(4);
  a.add(5);
  print(a);
}

However the cascade operator .. is here to make the code a be nicer. The operator apply a method on the receiver/object, discard the returned value of that method and instead returns the receiver/object itself.

void main(){
  var a = [1,2,3]
    ..add(4)
    ..add(5);
  print(a);
}

ref:

nelsonic commented 4 years ago

Hopefully the editor syntax highlighting will help us if we accidentally add a semicolon on the var line ...

void main(){
  var a = [1,2,3];
    ..add(4)
    ..add(5);
  print(a);
}

It's good that this exists for when variable names are longer ... but I see limited applicability in general. Whereas the Elixir |> is used everywhere! 💭 How many times are we going to declare a variable and then modify it on the next line? As mentioned yesterday in the Variables/Constants PR: https://github.com/dwyl/learn-dart/pull/4#discussion_r366949939, I think we are far more likely to use const and final and be disciplined about not mutating values.

Still totally worth adding this to the learnings in the README.md with the proviso that this is a language feature we know exists but we haven't found a valid use for yet. See: https://stackoverflow.com/a/17026173/1148249