简体   繁体   中英

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":

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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