104

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!

6 Answers 6

148

Just use contains

myFunction(strings.contains(myString))
2
35

And if you didn't want to use strict equality, you could use exists:


myFunction(strings.exists { x => customPredicate(x) })
23

Even easier!

strings contains myString
4
  • 5
    How is that different from the accepted answer? Jan 22, 2018 at 14:03
  • 6
    It's fundamentally the same but differences are: 1. Fewer brackets 2. Fewer periods 3. No reference to myFunction 4. more white space. Overall; My answer = 25 characters vs Accepted answer = 38 characters
    – Taylrl
    Jan 22, 2018 at 14:07
  • It was a rhetoric question ;) To give you a context I got here from LQP. I didn't recommend deletion, but if you post late answer try provide some additional value. A bit of syntactic sugar it doesn't feel like it, you know. Just saying... Jan 22, 2018 at 14:13
  • 4
    No problems. I understand. I think it does add value by showing increased simplicity. Thanks anyway though :)
    – Taylrl
    Jan 22, 2018 at 21:33
3

this should work also with different predicate

myFunction(strings.find( _ == mystring ).isDefined)
1
  • 4
    You could just use exists instead of having to use find combined with isDefined
    – Ciaran0
    Mar 7, 2016 at 23:21
2

In your case I would consider using Set and not List, to ensure you have unique values only. unless you need sometimes to include duplicates.

In this case, you don't need to add any wrapper functions around lists.

-1

You can also implement a contains method with foldLeft, it's pretty awesome. I just love foldLeft algorithms.

For example:

object ContainsWithFoldLeft extends App {

  val list = (0 to 10).toList
  println(contains(list, 10)) //true
  println(contains(list, 11)) //false

  def contains[A](list: List[A], item: A): Boolean = {
    list.foldLeft(false)((r, c) => c.equals(item) || r)
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.