避免在DART中复制无效检查
我目前的目标是删除此代码重复:
final int? myNullableInt = 10;
/// Everywhere I need to do this null verification:
if (myNullableInt == null) return null;
return someOtherMethodThatReceivesANonNullableInt(myNullableInt);
我想将其转换为Kotlin中的内容:
final int? myNullableInt = 10;
return myNullableInt?.apply((myInt) => someOtherMethodThatReceivesANonNullableInt(myInt));
我做到了:
extension ApplyIfNotNull on Object? {
T? apply<T extends Object?>(Object? obj, T? Function(Object) fn) {
if (obj == null) return null;
return fn(obj);
}
}
但这给了我静态错误:
The argument type 'Object' can't be assigned to the parameter type 'int'.
注意:这应该与所有类型一起使用,例如int s,
字符串
s,double
和myownClasStype
s。
我能做什么?还是我想念什么?
My current goal is to remove this code duplication:
final int? myNullableInt = 10;
/// Everywhere I need to do this null verification:
if (myNullableInt == null) return null;
return someOtherMethodThatReceivesANonNullableInt(myNullableInt);
I want to convert to something like we have in Kotlin:
final int? myNullableInt = 10;
return myNullableInt?.apply((myInt) => someOtherMethodThatReceivesANonNullableInt(myInt));
I did it:
extension ApplyIfNotNull on Object? {
T? apply<T extends Object?>(Object? obj, T? Function(Object) fn) {
if (obj == null) return null;
return fn(obj);
}
}
But this gives me a static error:
The argument type 'Object' can't be assigned to the parameter type 'int'.
Note: this should work with all types, e.g int
s, String
s, double
and MyOwnClassType
s.
Is there something I can do? or am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是行不通的,因为它声明回调能够接受任何
对象
参数,但是您可能会尝试将其与仅接受int
的函数一起使用。争论。还不清楚为什么您制作了扩展方法,因为它根本不涉及接收器(this
)。您还需要在回调的参数类型上使您的函数通用:(
这与我在 https://github.com/dart-lang/lange/langage/issues/360#issuecomment-502423488 ,但随着参数的反转。)
或作为扩展方法,以便它可以在
上使用此
,而不是拥有额外的obj
参数:另请参见 https://github.com/dart-lang/lange/sissues/360 对于现有的语言功能请求,以及此时其他建议的解决方法。
That doesn't work because it declares that the callback be capable of accepting any
Object
argument, but you're presumably trying to use it with a function that accepts only anint
argument. It's also unclear why you've made an extension method since it doesn't involve the receiver (this
) at all.You need to make your function generic on the callback's argument type as well:
(That's the same as what I suggested in https://github.com/dart-lang/language/issues/360#issuecomment-502423488 but with the arguments reversed.)
Or, as an extension method, so that it can work on
this
instead of having the extraobj
argument:Also see https://github.com/dart-lang/language/issues/360 for the existing language feature request and for some other suggested workarounds in the meantime.