Search code examples
javascriptscalalodashseq

Scala List equivalent of Lodash _.thru()


The Scala List API has a variety of functional methods similar to Lodash:

I am looking for the Scala equivalent of the Lodash .thru() function for chaining, which is like .map() except it is called once and passes in the entire list as an argument, rather than the individual items in the List.


Solution

  • Scala 2.13 introduced ChainingOps which provide pipe method, that makes probably what you expect.

    import scala.util.chainingOps._ //need to be imported, to make pipe available
    
    List(1,2,3)
       .pipe(l => 0 :: l) // List(0, 1, 2, 3)
    

    If you can't use Scala 2.13 yet, I would just fall back to pattern matching:

    List(1,2,3) match {
        case l => 0 :: l
    }