O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required