Scala's SeqLike
implement a method contains
. How can I cleanly implement a containsAny
feature?
Let's say I want to find out if a string string
contains any of the blacklisted characters in blacklist
:
val blacklist = List("(", ")", "[", "]", "{", "}", "<", ">")
string containsAny blacklist
How is the best way to implement the second line cleanly?
My version so far looks like this:
(blacklist.view map string.contains) contains true
Your best bet is to make the blacklist a set.
val blacklist = "()[]{}<>".toSet
Now you can use exists
to find if any of those characters exist in your string. Since Set[T]
extends T => Boolean
, you can just use the set directly instead of having to write 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
(Note: be careful about the difference between strings, "I am a string"
and characters: 'c'
. A one-character string is a string, not a character.)
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