dwyl / dwyl/learn-dart

The cascade operator ..

Open
#7 1 comment 2 reactions 0 assignees View on GitHub
enhancement
Dominant language
No language data
Stars
45
Forks
11
PR merge metrics
No merged PRs in 30d

Description

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

```elixir
"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:

```dart
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](https://api.dart.dev/stable/1.24.3/dart-core/List/add.html) as the following declaration:

```dart
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:

```dart
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.

```dart
void main(){
var a = [1,2,3]
..add(4)
..add(5);
print(a);
}
```
ref:
- https://dart.dev/guides/language/language-tour#cascade-notation-
- https://news.dartlang.org/2012/02/method-cascades-in-dart-posted-by-gilad.html
- https://stackoverflow.com/questions/17025769/how-do-method-cascades-work-exactly-in-dart

Contributor guide

No contributing guide indexed for this repository

Research direction

No target file or test is named. Start by reading the Dart cascade-notation documentation and the linked references, then determine where this explanation belongs; done means the lesson explains the `..` operator with the shown list examples and accurate references.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.