在Scala中,有一种简洁而简单的方法来比较一个值和多个值 [英] In Scala, is there a neat and simple way to compare one value with multiple values

查看:82
本文介绍了在Scala中,有一种简洁而简单的方法来比较一个值和多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个变量x,我想检查它是否等于多个值a,b,c,d,e中的任何一个(我的意思是==相等,不是同一性)。

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).

在SQL查询中,相同的概念使用

In an SQL query the same concept is handled with

WHERE x IN (a, b, c, d, e).

Scala中是否有类似的东西这么简单?我知道,否则可以用复杂的表达式在一行中完成此操作,例如构建HashSet并检查集合中是否存在,但是我更喜欢使用简单的结构(如果有)。

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.

推荐答案

相对于,我更希望包含(a)存在(_ == a )

I would prefer contains(a) over exists(_ == a):

scala> List(3, 4, 5) contains 4
res0: Boolean = true

scala> List(3, 4, 5) contains 6
res1: Boolean = false

更新: 包含 SeqLike ,因此以上内容适用于任何序列。

Update: contains is defined in SeqLike, so the above works with any sequence.

更新2: 包含 SeqLike 中:

def contains(elem: Any): Boolean = exists (_ == elem)

这篇关于在Scala中,有一种简洁而简单的方法来比较一个值和多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆