whenSafe<T> function

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

English: The when function of the Kotlin version of the method switch.
As long as the first true is found in Map.keys of conditionMap, its corresponding ValueGetter method will be executed immediately and the relative value will be returned.
If it is not found, you must set defaultValue, or use the when method

Special attention!!! Due to the characteristics of Map, you need to ensure that Map.keys in conditionMap does not have multiple true values. If you cannot guarantee it, it is recommended to use the whenTrue or whenBool method to avoid program problems

中文: 方法switch的kotlin版本的when函数.
只要在conditionMapMap.keys中发现第一个true,就会立刻执行其对应的ValueGetter方法,并返回相对的值.
如果没有找到的话,必须要设置defaultValue,或者使用when方法

特别注意!!! 由于Map的特性,需要确保conditionMap中的Map.keys不会出现多个true的值。 如果不能保证,建议使用whenTrue或者whenBool方法,这样可以避免程序出现问题

example:

String winner = when<String>({
  "Dart is Language".contains("UI"): () {
    return "Flutter";
  },
  "Flutter is UI Framework".contains("UI"): () {
    return "Flutter";
  },
});

Implementation

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