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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With