Wrapping it up

We need to add additional behavior to the existing code so as to address cross-cutting concerns. Logging is a cross-cutting concern, for example. We have an existing method whose arguments we need to log without modifying the method itself. Don't worry, we have currying to the rescue! Here is how the code looks:

object WrapItUp extends App { 
  def attach_logger[X, Y](f: (X) => Y)(arg: X): Y = { // 1
    println("arg = " + arg.toString) 
    println("Calling the function...") 
    val result = f(arg)  // 2
    println("function call returned...") 	

    result 
  } 

  def f1(i: Integer): Integer = i + 10 // 3
  def f2(s: String): String = s + " " + s // 4

  val f1WithArgsLogged = attach_logger(f1) _ // 5 - attach argument loggin 
 val f2WithArgsLogged ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.