Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The cascade operator .. #7

Open
SimonLab opened this issue Jan 16, 2020 · 1 comment
Open

The cascade operator .. #7

SimonLab opened this issue Jan 16, 2020 · 1 comment
Labels
enhancement New feature or request

Comments

@SimonLab
Copy link
Member

SimonLab commented Jan 16, 2020

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:

@SimonLab SimonLab added the enhancement New feature or request label Jan 16, 2020
@nelsonic
Copy link
Member

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: #4 (comment),
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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants