What is the idiomatic way to combine member function calls with other function calls in Scala?

81 Views Asked by At

Say we have an object (e.g. a list) in Scala, and we want to sequence user-defined functions with object member functions, for instance:

g(l.map(f)
   .foldRight(...))
 .map(h)

If the sequence of functions is larger, the code gets a little messy. Is there a better way to write such a code? Maybe something like:

l.map(f)
 .foldRight(...)
 .call(g)   // call would simply call function g on the resulting object
 .map(h)
1

There are 1 best solutions below

0
Dmytro Mitin On

Using scala.util.chaining._ you can re-write

trait A
trait B
trait C
trait D
trait E
val l:  List[A]      = ???
val f:  A => B       = ???
val z:  C            = ???
val op: (B, C) => C  = ???
val g:  C => List[D] = ???
val h:  D => E       = ???
g(l.map(f)
  .foldRight(z)(op))
.map(h)

as

import scala.util.chaining._

l.map(f)
  .foldRight(z)(op)
  .pipe(g)
  .map(h)

https://github.com/scala/scala/blob/v2.13.10/src/library/scala/util/ChainingOps.scala

https://blog.knoldus.com/new-chaining-operations-in-scala-2-13/

https://alvinalexander.com/scala/scala-2.13-pipe-tap-chaining-operations/