Dart 中是否有运算符或函数可以轻松验证数字是否在范围内?类似于 Kotlinin运算符:
https://kotlinlang.org/docs/reference/ranges.html
if (i in 1..10) { // equivalent of 1 <= i && i <= 10
println(i)
}
Run Code Online (Sandbox Code Playgroud)
小智 27
由于包含扩展函数,如果您可以进行非内联检查,则可以稍微更改此答案。
据我所知,没有内置函数可以实现这一点,但您可以轻松创建自己的扩展来num模拟这一点。
像这样的东西会模拟范围验证:
void main() {
final i = 2;
if (i.isBetween(1, 10)) {
print('Between');
} else {
print('Not between');
}
}
extension Range on num {
bool isBetween(num from, num to) {
return from < this && this < to;
}
}
Run Code Online (Sandbox Code Playgroud)
这种方法尤其是 from 和 to 都是互斥的,但通过细微的调整和更好的命名,您可以轻松地为所有 Kotlin 范围检查创建扩展函数。
小智 5
I find using clamp more readable. So, to check if i is between 1 and 10, clamp it to the range and compare to itself.
if (i.clamp(1,10) == i) {
print(i);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6348 次 |
| 最近记录: |