简体   繁体   English

Scala相当于Python的“in”运算符集合?

[英]Scala equivalent of Python's “in” operator for sets?

In Scala, it's possible to check if an item is a member of a Set using "Contains": 在Scala中,可以使用“Contains”检查项目是否是Set的成员:

object Main extends App {
    val the_set = Set(1, 2, 3, 4)
    if( the_set contains 3 ) println("The set contains 3!")
}

However, I'd like to do a similar comparison but with the item coming first and the set coming at the end (a minor stylistic point, I know). 但是,我想做一个类似的比较,但是首先是项目,最后是设置(我知道一个小的风格点)。 I have some background in Python, so I'm hoping for something along the lines of Python's in operator: 我有一些Python的背景,所以我希望运算符的Python 有一些东西:

the_set = set([1, 2, 3, 4])
if 3 in the_set: print "The set contains 3!"

Is there any way to do this in Scala? 在Scala有什么办法吗? In case you're curious, the reason why I want to do this is to write a concise if statement that compares a value against a long Set that I build. 如果你很好奇,我想要这样做的原因是编写一个简洁的if语句,将一个值与我构建的long Set进行比较。 At the same time, I want the item to come first so that the code is easier to read and understand. 同时,我希望项目首先出现,以便代码更易于阅读和理解。

Thanks! 谢谢!

Here is one example how to do this: 以下是如何执行此操作的一个示例:

scala> implicit class InOperation[T](v: T) extends AnyVal { def in(s: Set[T]) = { s contains v } }
defined class InOperation

scala> val x = Set(1,2,3)
x: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

scala> 2 in x
res0: Boolean = true

It uses implicit class to add in method (that takes Set[T] ) to arbitrary type T and checks whether object is in the set. 它使用隐式类添加in方法(这需要Set[T]以任意类型T并检查物体是否是在该组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM