How to find a matching element in a list and map it in as an Scala API method?

后端 未结 4 449
被撕碎了的回忆
被撕碎了的回忆 2021-02-05 06:42

Is there a method to do the following without doing both methods: find and map?

val l = 0 to 3
l.find(_ * 33 % 2 == 0).map(_ * 33) //          


        
4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 07:19

    Hey look, it's my little buddy findMap again!

    /**
     * Finds the first element in the list that satisfies the partial function, then 
     * maps it through the function.
     */
    def findMap[A,B](in: Traversable[A])(f: PartialFunction[A,B]): Option[B] = {
      in.find(f.isDefinedAt(_)).map(f(_))
    }
    

    Note that, unlike in the accepted answer, but like the collectFirst method mentioned in one of its comments, this guy stops as soon as he finds a matching element.

提交回复
热议问题