在Scala中,有没有一种简洁明了的方法来比较一个值与多个值
假设我有一个变量 x,我想检查它是否等于多个值 a、b、c、d、e 中的任何一个(我的意思是 == 相等,而不是恒等)。
在 SQL 查询中,相同的概念可以通过
WHERE x IN (a, b, c, d, e).
Scala 中是否有类似的东西来处理,就这么简单?我知道可以使用复杂的表达式在一行中完成此操作,例如构建 HashSet 并检查集合中是否存在,但我更愿意使用简单的构造(如果可用)。
Say I have a variable x, and I want to check if it's equal to any one of multiple values a, b, c, d, e (I mean the == equality, not identity).
In an SQL query the same concept is handled with
WHERE x IN (a, b, c, d, e).
Is there something equivalent in Scala that's as straightforward as that? I know it's otherwise possible to do it in one line with a complex expression such as building a HashSet and checking for existence in the set, but I'd prefer to use a simple construct if it's available.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以按如下方式实现
in
运算符:You could implement an
in
operator as follows:我更喜欢
contains(a)
而不是exists(_ == a)
:更新:
contains
是在SeqLike
,所以上面的代码适用于任何序列。更新2:这是
包含
在SeqLike
中:I would prefer
contains(a)
overexists(_ == a)
:Update:
contains
is defined inSeqLike
, so the above works with any sequence.Update 2: Here is the definition of
contains
inSeqLike
:假设
Set[A]
也是A => Boolean
,你可以说:为此定义一些 pimpin' 糖实际上非常好:
然后你可以像这样编写代码:
Given that a
Set[A]
is also aA => Boolean
, you can just say:It's actually quite nice to define some pimpin' sugar for this:
Then you can write the code like so:
通过综合所有其他答案,我得出了正确答案:
Ta-da。
By synthesizing all the other answers, I have come up with the correct answer:
Ta-da.
存在:
查找和过滤接近:
与其他答案一样,我的第一个答案是使用 contains:
但后来我想,它只适用于像 4 这样的装箱值,不适用于区分身份和相等的类。为了证明这一点,我写了一个小类,这证明我错了::)
我明白了,我必须更频繁地使用 equals/eq/== ,才能将这些区别带入我的大脑。
恕我直言,答案是最简单的。
exists:
find and filter come close:
My first answer was, as other answers, to use contain:
but then I thought, it would only work for boxed values like 4, not for classes, which distinguish identity and equality. To prove it, I wrote a small class, which proved me wrong: :)
I see, I have to use equals/eq/== more often, to get the distinctions into my brain.
is imho the answer which is most easy.
Set(a, b, c, d, e)(x)
也有效。我将把这样做的原因留给读者作为练习。 :-)Set(a, b, c, d, e)(x)
works as well. I'll leave the reasons for it as an exercise to the reader. :-)也适用于 Scala 3 的解决方案:(
我更新其他解决方案之一的请求被拒绝。)
Solution which also works with Scala 3:
(My request to update one of the other solutions was rejected.)