whenTrueSafe<T> function

T whenTrueSafe<T>(
  1. Map<ValueGetter<bool>, ValueGetter<T>> conditionMap, {
  2. ValueGetter<T>? defaultValue,
})

English: The when function of the Kotlin version of the method switch,its conditional expression will be calculated。.
As long as conditionMap to Map.keys appears first execution result is true, it will immediately perform corresponding ValueGetter method, and an opposite return value.
If it is not found, it will return null; if you need a default value, you can add a MapEntry with a key equal to true at the end of the Map

中文: 方法switch的kotlin版本的when函数.
,其条件表达式会进行计算。 只要在conditionMapMap.keys中第一个出现执行结果为true,就会立刻执行其对应的ValueGetter方法,并返回相对的值.
如果没有找到的话,会返回null;如果需要默认值,可以在Map中最后加入一个key等于true的MapEntry

example:

String something = whenTrue<String>({
     () {
   if (1 + 100 * 1000 < 2000) {
     return false;
   } else if ("Who is my lovely baby?".length > 10) {
     return true;
   } else {
     return false;
   }
 }: () {
   return "Test OK";
 },
     () {
   return int.tryParse("3.14*") != null;
 }: () {
   return "PI get";
 }
});

Implementation

T whenTrueSafe<T>(Map<ValueGetter<bool>, ValueGetter<T>> conditionMap,
    {ValueGetter<T>? defaultValue}) {
  for (var element in conditionMap.entries) {
    if (element.key.call()) {
      return element.value();
    }
  }
  assert(
      defaultValue != null,
      "If you want to use the [whenTrueSafe] method, please make sure it can be executed in the [conditionMap], or set the [defaultValue] function;"
      " of course, you can also directly use the [whenTrue] method to get the return value that may be empty");
  return defaultValue!.call();
}