如何在 Dart 中制作更通用的 isEmpty() 函数?
How can I make a more generic isEmpty() function in Dart?
我有以下实用函数来检查 String
变量是否为空或 null:
bool isEmpty(String s){
return (s??'').isEmpty;
}
现在我想为 Iterable
做一个类似的功能。实现很简单:
bool isEmpty(Iterable i){
return (i??[]).isEmpty;
}
但现在我必须以不同的方式命名这两个函数,或者以某种方式将它们合并为一个。这就是我 运行 遇到麻烦的地方。
我可以让变量dynamic
:
bool isEmpty(dynamic x){
if( x is String) return (x??'').isEmpty;
if( x is Iterable) return (x??[]).isEmpty;
throw UnimplementedError('isEmpty() is not defined for the type ${x.runtimeType}');
}
但是如果我通过 String s = null
或 Set s = null
,那么 x 将是 Null
类型。如果将来我想对 Iterable
和 String
区别对待 null
怎么办?
我可以使函数通用:
bool isEmpty<T>(T x){
if( T == String) return ((x as String)??'').isEmpty;
if( T == Iterable) return ((x as Iterable)??[]).isEmpty;
throw UnimplementedError('isEmpty() is not defined for the type $T');
}
但现在如果我传递 List
、Set
或任何其他 Iterable
的 子类型 ,它将抛出异常, 但不是 实际 Iterable
.
我怎样才能使一个 isEmpty()
函数与接受 String
和 Iterable
的两个独立函数完全相同?
您可以进行扩展。喜欢这些:
extension StringExt on String {
bool isNullOrEmpty() => this == null || this.isEmpty;
}
extension IterableExt<T> on Iterable<T> {
bool isNullOrEmpty() => this == null || this.isEmpty;
}
由于名称冲突,我已将 isEmpty
重命名为 isNullOrEmpty
(String.isEmpty, Iterable<T>.isEmpty
...)。
我有以下实用函数来检查 String
变量是否为空或 null:
bool isEmpty(String s){
return (s??'').isEmpty;
}
现在我想为 Iterable
做一个类似的功能。实现很简单:
bool isEmpty(Iterable i){
return (i??[]).isEmpty;
}
但现在我必须以不同的方式命名这两个函数,或者以某种方式将它们合并为一个。这就是我 运行 遇到麻烦的地方。
我可以让变量dynamic
:
bool isEmpty(dynamic x){
if( x is String) return (x??'').isEmpty;
if( x is Iterable) return (x??[]).isEmpty;
throw UnimplementedError('isEmpty() is not defined for the type ${x.runtimeType}');
}
但是如果我通过 String s = null
或 Set s = null
,那么 x 将是 Null
类型。如果将来我想对 Iterable
和 String
区别对待 null
怎么办?
我可以使函数通用:
bool isEmpty<T>(T x){
if( T == String) return ((x as String)??'').isEmpty;
if( T == Iterable) return ((x as Iterable)??[]).isEmpty;
throw UnimplementedError('isEmpty() is not defined for the type $T');
}
但现在如果我传递 List
、Set
或任何其他 Iterable
的 子类型 ,它将抛出异常, 但不是 实际 Iterable
.
我怎样才能使一个 isEmpty()
函数与接受 String
和 Iterable
的两个独立函数完全相同?
您可以进行扩展。喜欢这些:
extension StringExt on String {
bool isNullOrEmpty() => this == null || this.isEmpty;
}
extension IterableExt<T> on Iterable<T> {
bool isNullOrEmpty() => this == null || this.isEmpty;
}
由于名称冲突,我已将 isEmpty
重命名为 isNullOrEmpty
(String.isEmpty, Iterable<T>.isEmpty
...)。