繁体   English   中英

避免在 Dart 中重复进行空类型检查

[英]Avoid duplication of null type checking in 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、 String s、 doubleMyOwnClassType s。

有什么我可以做的吗? 还是我错过了什么?

extension ApplyIfNotNull on Object? { T? apply<T extends Object?>(Object? obj, T? Function(Object) fn) { if (obj == null) return null; return fn(obj); } }

这不起作用,因为它声明回调能够接受任何Object参数,但您可能正在尝试将它与仅接受int参数的函数一起使用。 还不清楚为什么您制作了扩展方法,因为它根本不涉及接收器( this )。

您还需要在回调的参数类型上使您的函数通用:

R? applyIfNotNull<R, T>(T? obj, R Function(T) f) =>
    (obj == null) ? null : f(obj);

(这与我在https://github.com/dart-lang/language/issues/360#issuecomment-502423488中的建议相同,但参数颠倒了。)

或者,作为一种扩展方法,这样它就可以处理this而不是使用额外的obj参数:

extension ApplyIfNotNull<T> on T? {
  R? apply<R>(R Function(T) f) {
    // Local variable to allow automatic type promotion.  Also see:
    // <https://github.com/dart-lang/language/issues/1397>
    var self = this;
    return (self == null) ? null : f(self);
  }
}

另请参阅https://github.com/dart-lang/language/issues/360了解现有语言功能请求以及其他一些建议的解决方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM