DART:推断仿制药中的不可废型
我有两个通用类,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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论