Idiomatic implementation of containsAny for Scala SeqLike

Scala SeqLikeimplement the method contains. How can I purely implement a function containsAny?

Let's say I want to find out if a string contains stringany of the blacklists in blacklist:

val blacklist = List("(", ")", "[", "]", "{", "}", "<", ">")
string containsAny blacklist

What is the best way to implement the second line cleanly?

My version looks like this:

(blacklist.view map string.contains) contains true
+5
source share
1 answer

It’s best to make the blacklist a set.

val blacklist = "()[]{}<>".toSet

Now you can use existsto find if any of these characters exist in your string. Since Set[T]extends T => Boolean, you can simply use the set directly, instead of writing an explicit condition.

scala> "I like fish (but not herring)" exists blacklist
res1: Boolean = true

scala> "I like fish, especially salmon!" exists blacklist
res2: Boolean = false

(: , "I am a string" : 'c'. - , .)

+10

All Articles