scalafunctional-programmingpure-function

Scala: passing impure function to a HoF


I came across a piece of scala code which makes use of map function in a very unexpected manner:

myList.map(item => someImpureFunction(item))

someImpureFunction has return type Unit.

Is it an acceptable way of doing FP?


Solution

  • If someImpureFunction returns Unit it implies that the function performs some side effect e.g. writes to a database or standard output, so in that case, it's better to use:

    myList.foreach(item => someImpureFunction(item))
    

    If you want to write pure FP code you should take a look at deferring the execution of side effects (a good example is Cats IO)