Scala check if element is present in a list

Dario Oddenino picture Dario Oddenino · Jan 10, 2013 · Viewed 137.9k times · Source

I need to check if a string is present in a list, and call a function which accepts a boolean accordingly.

Is it possible to achieve this with a one liner?

The code below is the best I could get:

val strings = List("a", "b", "c")
val myString = "a"

strings.find(x=>x == myString) match {
  case Some(_) => myFunction(true)
  case None => myFunction(false)
}

I'm sure it's possible to do this with less coding, but I don't know how!

Answer

Kim Stebel picture Kim Stebel · Jan 10, 2013

Just use contains

myFunction(strings.contains(myString))