Scala 中可以匹配范围吗?
Scala 中是否可以匹配一系列值?
例如:
val t = 5
val m = t match {
0 until 10 => true
_ => false
}
如果 t
介于 0 和 10 之间,则 m
将为 true
,否则为 false。当然,这一点是行不通的,但是有什么办法可以实现这样的目标吗?
Is it possible to match a range of values in Scala?
For example:
val t = 5
val m = t match {
0 until 10 => true
_ => false
}
m
would be true
if t
was between 0 and 10, but false otherwise. This little bit doesn't work of course, but is there any way to achieve something like it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用
Range
进行防护:Guard using
Range
:您可以使用守卫:
You can use guards:
通过这些定义:
您可以执行如下检查:
因此您需要的代码是:
With these definitions:
You can do checks like these:
So the code you need would be:
这是使用范围进行匹配的另一种方法:
Here's another way to match using a range:
另一种选择是使用隐式将其实际添加到语言中,我为 int 和 Range 添加了两种变体
Another option would be to actually add this to the language using implicits, i added two variations for int and Range