Search code examples
scalafunctional-programmingpointfree

The case for point free style in Scala


This may seem really obvious to the FP cognoscenti here, but what is point free style in Scala good for? What would really sell me on the topic is an illustration that shows how point free style is significantly better in some dimension (e.g. performance, elegance, extensibility, maintainability) than code solving the same problem in non-point free style.


Solution

  • Quite simply, it's about being able to avoid specifying a name where none is needed, consider a trivial example:

    List("a","b","c") foreach println
    

    In this case, foreach is looking to accept String => Unit, a function that accepts a String and returns Unit (essentially, that there's no usable return and it works purely through side effect)

    There's no need to bind a name here to each String instance that's passed to println. Arguably, it just makes the code more verbose to do so:

    List("a","b","c") foreach {println(_)}
    

    Or even

    List("a","b","c") foreach {s => println(s)}
    

    Personally, when I see code that isn't written in point-free style, I take it as an indicator that the bound name may be used twice, or that it has some significance in documenting the code. Likewise, I see point-free style as a sign that I can reason about the code more simply.