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

后端 未结 4 447
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  死守一世寂寞
    2021-02-05 07:25

    How about using collect?

    // Returns List(66)
    List(1, 2, 3) collect { case i if (i * 33 % 2 == 0) => i * 33 }
    

    However that will return all matches and not just the first one.

    The better answer would have been, based on Scala 2.9:

    // Returns Some(66)
    List(1, 2, 3) collectFirst { case i if (i * 33 % 2 == 0) => i * 33 }
    

    The solution suggested in the comments to append a head to get a Scala 2.8 version of that is not very efficient, I'm afraid. Perhaps in that case I would stick to your own code. In any case, in order to make sure it returns an option, you should not call head, but headOption.

    // Returns Some(66)
    List(1, 2, 3) collect { case i if (i * 33 % 2 == 0) => i * 33 } headOption
    

提交回复
热议问题