whenTrue<T> function
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函数.
,其条件表达式会进行计算。
只要在conditionMap
的Map.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? whenTrue<T>(Map<ValueGetter<bool>, ValueGetter<T>> conditionMap) {
for (var element in conditionMap.entries) {
if (element.key.call()) {
return element.value();
}
}
return null;
}