dart-lang / dart-lang/language

Allow non-nullable optional arg for generic type

Open
#2,906 5 comments 0 reactions 0 assignees View on GitHub
request
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

Functions like `void foo([T optionalArg])` could only have `optionalArg` as nullable (`T?`).

Optional arg could only be non-nullable if there is a known const default value, but this is never the case for generics.

I've tried something like this as a workaround:

```dart
void foo([T optionalArg.= const Object() as T]) {}
```

The reasoning behind that workaround is "whenever the arg is not provided – I'm ok to downcast `T` to `Object`.

Analyzer didn't give any warnings about this code, however, build failed with the following error:

```
void foo([T value = const Object() as T]) {}
^
Target kernel_snapshot failed: Exception
```

This could have been solved with a default types for type arguments, so something like this:

```
void foo([T dep = const Object]) {}
```
Are there any plans on adding default types? What would be a language construct that indicates that something is optional to provide, but when provided – should not be null?

Contributor guide

Open the contributing guide

Research direction

Start by reviewing the issue's examples of generic optional parameters, non-nullability, and proposed default type arguments. Done would require a decided language construct and documented behavior for optional generic arguments; no source files or tests are named in the issue.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.