DART:推断仿制药中的不可废型

发布于 2025-01-27 00:33:07 字数 1490 浏览 2 评论 0原文

我有两个通用类,streamProcessor需要接受无效的类型作为通用参数,同时还维护了不可撤消的参数化属性:

/// [T] must not be nullable (the data can not be null).
class DataProcessor<T extends Object> { /* ... */ }

/// [T] can be nullable if stream sends a checkpoint without any data attached.
class StreamProcessor<T extends Object?> {
  final DataProcessor<T> dataStream;
  //                  ^ 
  // Error: 'T' doesn't conform to the bound 'Object' of the type parameter 'T'.

  /// These events may be nullable or non-nullable, depending on the
  /// type of object passed to the constructor.
  final Stream<T> bareEventsStream;

  StreamProcessor(Stream<T> events) :
    dataStream = DataProcessor(events.where((e) => e != null)) { /* ... */ }
}

编译器对这种情况非常不满(请参阅以下情况(请参阅以下方式”(请参阅​​“请参见”错误“评论)。我可以通过限制streamProcessor将参数键入到不可用的类型(扩展对象),然后声明bareeventsStream来使其更加快乐。流&lt; t?&gt;。但是,在这种情况下,如果streamProcessor的用户使用不可用的类型(例如:streamProcessor&lt; int&gt;),则将是bareeventsStream将是a 流&lt; int?&gt;,强迫他们在整个代码上使用(null Check Operator),没有充分的理由,这似乎向后倾斜以使声音无效。

是否存在类似于t?的语法,从通用参数中推断出不可删除的类型(在可能的情况下)?

ps这与 dart-lang/langagans#143 但我需要那里讨论的内容的“相反”。

I have two generic classes, and StreamProcessor needs to accept a nullable type as a generic parameter, while also maintaining a parametrized property which isn't nullable:

/// [T] must not be nullable (the data can not be null).
class DataProcessor<T extends Object> { /* ... */ }

/// [T] can be nullable if stream sends a checkpoint without any data attached.
class StreamProcessor<T extends Object?> {
  final DataProcessor<T> dataStream;
  //                  ^ 
  // Error: 'T' doesn't conform to the bound 'Object' of the type parameter 'T'.

  /// These events may be nullable or non-nullable, depending on the
  /// type of object passed to the constructor.
  final Stream<T> bareEventsStream;

  StreamProcessor(Stream<T> events) :
    dataStream = DataProcessor(events.where((e) => e != null)) { /* ... */ }
}

The compiler is rightfully unhappy about this situation (see the "Error" comment). I can make it happier by restricting the StreamProcessor type argument to a non-nullable type (extends Object) and then declaring bareEventsStream as Stream<T?>. But in that case, if the user of StreamProcessor uses a non-nullable type (e.g.: StreamProcessor<int>), the bareEventsStream will be a Stream<int?>, forcing them to use ! (null check operator) all over the code without a good reason, which seems backwards to sound null safety.

Is there a syntax which would, similarly to how T? infers a nullable type, infer a non-nullable type (when possible) from a generic parameter?

P.S. This is somewhat related to dart-lang/language#143 but I need "an opposite" of what's being discussed there.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文