Scala 相当于 Python 的“in"集合运算符? [英] Scala equivalent of Python's "in" operator for sets?

查看:99
本文介绍了Scala 相当于 Python 的“in"集合运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala 中,可以使用Contains"来检查项目是否是 Set 的成员:

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!")
}

然而,我想做一个类似的比较,但首先是项目,最后是系列(我知道这是一个次要的风格点).我在 Python 方面有一些背景,所以我希望得到一些类似于 Python 的 in 运算符的东西:

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

在 Scala 中有没有办法做到这一点?如果您感到好奇,我之所以要这样做是为了编写一个简洁的 if 语句,将一个值与我构建的长 Set 进行比较.同时,我希望项目在前,这样代码更容易阅读和理解.

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.

谢谢!

推荐答案

这是一个如何执行此操作的示例:

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

它使用隐式类来添加 方法(需要 Set[T])到任意类型 T 并检查对象是否在集合中.

It uses implicit class to add in method (that takes Set[T]) to arbitrary type T and checks whether object is in the set.

这篇关于Scala 相当于 Python 的“in"集合运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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