Scala Range contains(elem: Any) 方法
显然 Range
有一个方法可以检查它是否包含 Any 类型的值。我知道它来自 SeqLike
,但会导致一些问题。
例如,我正在匹配 joda.DateTime 中的小时:
DateTime.now match {
case d if 0 to 12 contains d.hourOfDay() => ...
这里 d.hourOfDay() 返回 DateTime.Property,而不是 Int,但代码仍然可以编译,因为 contains(elem: Any)
。有什么方法可以在编译时检查此类调用吗?
Apparently Range
has a method that checks if it contains a value of type Any. I understand that it is from SeqLike
, but causes some problems.
For instance, i was matching hours from joda.DateTime:
DateTime.now match {
case d if 0 to 12 contains d.hourOfDay() => ...
Here d.hourOfDay() returns DateTime.Property, not Int, but code still compiles, because of contains(elem: Any)
. Is there any way to check for such calls at compile time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将 Scalaz 的类型安全 equals (
===
) 与TraversableOnce
上的exists
方法结合使用。You can use Scalaz's typesafe equals (
===
) in conjunction withexists
method onTraversableOnce
.您可以 pimp
Range
添加类型-safer contains 方法:导入隐式并在任何范围实例上调用
safeContains
:You can pimp
Range
to add a type-safer contains method:Import the implicit and call
safeContains
on any range instance:基于 Range 的 scaladocs 它看起来像没有更好的 Range 方法可以使用。您的选择似乎是
使用显式类型签名:
创建您自己的方法:
这似乎是 Java
equals
成为前泛型的延续,并且只是这一事实给 Scala 带来的不便之一。Based on the scaladocs for Range it looks like there's not a better Range method you could use. Your options seem to be
Use an explicit type signature:
Make your own method:
This seems to be a holdover from Java
equals
being pre-generics, and is only one of the inconveniences this fact causes for Scala.