Home > Net >  Nullable evaluation of function with non-null arguments
Nullable evaluation of function with non-null arguments

Time:08-25

S? _nullableEvaluation<S, T>(S Function(T) f, T? nullableArgument) =>
  nullableArgument == null ? null : f(nullableArgument);

Is there something in the dart language like the above, some built-in language feature? Not that it's hard to write yourself, just wondering if I'm reinventing the wheel to do something like the below.

import 'dart:convert';

void main() {
  String? test = null;
  print(_nullableEvaluation(utf8.encode, test));
  test = "Test";
  print(_nullableEvaluation(utf8.encode, test));
}

CodePudding user response:

There is nothing in the language which allows you to gate a call to a static function depending on the nullability of the argument.

However, if you write your static function as an extension method instead, you can use normal null-aware method invocation:

extension UtfEncode on String { 
  Uint8List utf8Encode() => utf8.encode(this);
}
// ...
   test?.utf8Encode()

You can also declare an extension method where you supply the function to call:

extension ApplyTo<T extends Object> on T {
  S applyTo<S>(S Function(T) f) => f(this);
}

which you can then use as:

  test?.applyTo(utf8.encode)
  • Related