Scala check if element is present in a list

后端 未结 6 1935
刺人心
刺人心 2021-01-30 19:45

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 c

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-30 19:55

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

提交回复
热议问题