Comments (2)
I found myself using this a few times. Although I think pattern matching
or at least a switch case with return type
will land in Dart in the next 2 years, this can work as a neat temporary solution.
I'd like to hear your opinion on a slightly different API. When I use this pattern I use Functions as my cases. The trailing braces ()
in your API don't look nice. I'm also not 100% satisfied with the default argument. I wish it would be a named argument but as default
is a reserved word, that's kind of impossible.
Original
- dartfmt with
??
is strange - When using functions - to prevent unnecessary constructor calls - on has to add
()
to the end - with
defaultValue
param better formatted. But using??
has the same effect with less allocations - defaultValue isn't named, hard to understand
// Original Proposal
_counter.switchCase({
1: Text("It's one"),
2: Text("It's two"),
3: Text("It's three"),
}) ??
Text("Other number"),
// Original Proposal with default
_counter.switchCase(
{
1: Text("It's one"),
2: Text("It's two"),
3: Text("It's three"),
},
Text("Other number"),
),
// Original Proposal with functions
_counter.switchCase(
{
1: () => Text("It's one"),
2: () => Text("It's two"),
3: () => Text("It's three"),
},
() => Text("Other number"),
)(),
Proposal 2
- forces users to use functions
- no trailing
()
- doesn't improve
??
dartformat handling - fallback case is clear
// Proposal 2 - forced functions
_counter.switchCase2({
1: () => Text("It's one"),
2: () => Text("It's two"),
3: () => Text("It's three"),
}) ??
Text("Other number"),
// Proposal 2 with default
_counter.switchCase2(
{
1: () => Text("It's one"),
2: () => Text("It's two"),
3: () => Text("It's three"),
},
fallback: () => Text("Other number"),
),
Proposal 3
- dense code with
defaultTo
match()
is boilerplate compared to Original solution- I have to admit that I like the closing
match()
for some reason. Maybe because of Pascals begin/end? 🤷 - Doesn't solve the
??
formatting, but users don't have to use it.
// Proposal 3 - match or error
_counter.switchCase3({
0: () => Text("zero"),
1: () => Text("It's one"),
2: () => Text("It's two"),
3: () => Text("It's three"),
}).match(),
// Proposal 3 - no default, but null (dartfmt 😖)
_counter.switchCase3({
1: () => Text("It's one"),
2: () => Text("It's two"),
3: () => Text("It's three"),
}).matchOrNull() ??
Text("Other number"),
// Proposal 3 with explicit default
_counter.switchCase3({
1: () => Text("It's one"),
2: () => Text("It's two"),
3: () => Text("It's three"),
}).defaultTo(() => Text("Other number")),
Implementation
Not that interesting, and very likely to change.
extension switchInt on int {
T switchCase<int, T>(Map<int, T> cases, [T defaultValue]) {
if (cases.containsKey(this)) return cases[this];
return defaultValue;
}
T switchCase2<int, T>(Map<int, T Function()> cases, {T Function() fallback}) {
if (cases.containsKey(this)) return cases[this]();
if (fallback == null) return null;
return fallback();
}
SwitchCase<T> switchCase3<int, T>(Map<int, T Function()> cases) {
if (cases.containsKey(this)) return SwitchCase.match(cases[this]());
return SwitchCase.noMatch();
}
}
class SwitchCase<T> {
SwitchCase.match(this.value) : matched = true;
SwitchCase.noMatch()
: matched = false,
value = null;
final T value;
final bool matched;
T match() {
if (matched) return value;
throw "no default argument";
}
T matchOrNull() {
if (matched) return value;
return null;
}
T defaultTo(T Function() fallback) {
if (!matched) return fallback();
return value;
}
}
Does someone have more ideas?
from dartx.
Hmm, I like some of your implementations, but not sure if those proposals really improve it's ease of use over the original. The goal would be as little typing as possible, without extra fields needed, and adding the additional syntax for the optional defaultValue seems to complicate it visually. I agree about there being another way to do the switch case more integrated into the Dart language in the way that the if's are like isTrue ? true : false with an inline method and some creative syntax (I've tried to visualize the best format of that for years), but until then this is a nice simple shortcut method.
You could include more than one implementation method so users can pick which switch they prefer for their case. If I had to choose, I liked Proposal 2 with default Maybe there's another simple option too, I'm thinking about it but your call what goes in your package..
from dartx.
Related Issues (20)
- Iterable.startsWith HOT 2
- Map.mapValue/mapKey HOT 2
- Null Safety Migration HOT 10
- Proposal: modifyWhere and modifyFirstWhere HOT 1
- pub get fails after upgrading flutter version for app developed with previous flutter version HOT 1
- Linear complexity of elementAt HOT 2
- Extension for text coloring based on luminance
- Create proper documentation for dartx HOT 2
- Improve README HOT 3
- Flatten should work with deeply nested lists as well
- Class 'List<List<int>>' has no instance method 'flatten'. Receiver: Instance(length:1) of '_GrowableList' Tried calling: flatten()
- More detailed and clear documentation
- Release update on pub HOT 3
- String isNullOrBlank missing HOT 1
- `takeFirst` and `takeLast` are not index safe HOT 1
- SSL Cert expired HOT 2
- `move` methods on `List` HOT 1
- Feature Request "IndicesWhere" HOT 2
- Update to support flutter 3.10 propoerly and upgrade depedencies HOT 1
- No more updates ? HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from dartx.