|
|
|
|
|
by munificent
994 days ago
|
|
We recently added pattern matching to Dart [1], so I'm always keen to see how it compares to similar features in other languages. In case it's interesting, here's that Ruby example ported to Dart: print(switch ({'name': 'John', 'friends': [{'name': 'Jane'}, {'name': 'Rajesh'}]}) {
{'friends': [{'name': var firstFriend}, ...]} => "matched: $firstFriend",
_ => "not matched"
});
Pretty similar! The main differences are that Dart doesn't have symbols, so the keys are string literals instead. Also, variable bindings in patterns are explicit (using "var") here to disambiguate them from named constant patterns.[1]: https://medium.com/dartlang/announcing-dart-3-53f065a10635 |
|
I've been using that and I love it, in general... but can I ask you why do we need to name a variable in a pattern like this:
That's the only thing that feels a bit annoying as you have to rename the variable... In Java, this would be something like: EDIT: I guess it's to support `Person(name: 'literal')` matches.> Dart doesn't have symbols
That's weird, as I actually use sometimes `#sym` (which has type `Symbol`)??
This prints `Symbol` :)I know you know Dart in and out, but could you explain why this is not actually a symbol in the way Ruby symbols are?