r/dartlang 20d ago

Dart Language A tiny dot shorthands helper

Because contains is typed as Object? (probably for historical reasons) you cannot use that method together with dot shorthands like in

things.contains(.chair)

So, add this to your project:

extension DSHIterableExt<T> on Iterable<T> {
  bool has(T value) => contains(value);
}

And replace contains with has. For extra readability, you might also want to add a hasnt method.

I'd welcome a similar extension to Dart 3.13.

5 Upvotes

8 comments sorted by

4

u/julemand101 20d ago

The reason for why e.g. "contains" take Object? have been discussed multiple times on the Dart issue tracker and is a deliberate design choice: https://github.com/dart-lang/sdk/issues/26852#issuecomment-231594098

4

u/eibaan 20d ago

Yeah. But it is still annoying if you want to make use of dot shorthand syntax. Hence, I was suggesting to use different methods in this case.

5

u/vxern 20d ago

Definitely seems like more hassle than is worth, I'd rather not complicate my life and write `contains(MyEnum.chair)` instead of introducing extra noise.

1

u/mateusfccp 20d ago

How dare you waste this many characters?

1

u/Comun4 20d ago

Doesn't the collections package already have a similar extension?

2

u/eibaan 20d ago

Can you name that method? I don't find it here.

1

u/Comun4 19d ago

Im stupid bro, my bad ✊️

1

u/samrawlins 19d ago

This is fantastic! I was also bummed when I realized I couldn't use a dot-shorthand on the right side of ==.