0

Scala - Partially Applied Functions. What is the use of Partially Applied Functions and How it works.

want to convert it into Partially Applied Functions.

def log(date: Date, message: String)  = {
      println(date + "----" + message)
   }

1 Answer 1

3

When you invoke a function, you're said to be applying the function to the arguments. If you pass all the expected arguments, you have fully applied it. If you send only a few arguments, then you get back a partially applied function. This gives you the convenience of binding some arguments and leaving the rest to be filled in later.

Example : The log( ) method takes two parameters: date and message. We want to invoke the method multiple times, with the same value for date but different values for message. We can eliminate the noise of passing the date to each call by partially applying that argument to the log( ) method. To do so, we first bind a value to the date parameter and leave the second parameter unbound by putting an underscore at its place. The result is a partially applied function that we've stored in a variable.

Try the following example

object Demo {
   def main(args: Array[String]) {
      val date = new Date
      val logWithDateBound = log(date, _ : String)

      logWithDateBound("message1" )
      Thread.sleep(1000)

      logWithDateBound("message2" )
      Thread.sleep(1000)

      logWithDateBound("message3" )
   }

   def log(date: Date, message: String) = {
      println(date + "----" + message)
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.