Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Share this Page URL

Chapter 8: Functions and Closures > 8.6 Partially applied functions - Pg. 149

S ECTION 8.6 · Partially applied functions in the function literal at most once. Multiple underscores mean multiple pa- rameters, not reuse of a single parameter repeatedly. The first underscore represents the first parameter, the second underscore the second parameter, the third underscore the third parameter, and so on. 8.6 Partially applied functions Although the previous examples substitute underscores in place of individual parameters, you can also replace an entire parameter list with an underscore. For example, rather than writing println(_) , you could write println _ . Here's an example: someNumbers.foreach(println _) Scala treats this short form exactly as if you had written the following: someNumbers.foreach(x => println(x)) Thus, the underscore in this case is not a placeholder for a single parameter. It is a placeholder for an entire parameter list. Remember that you need to leave a space between the function name and the underscore, because otherwise the compiler will think you are referring to a different symbol, such as for example, a method named println_ , which likely does not exist. When you use an underscore in this way, you are writing a partially ap- plied function. In Scala, when you invoke a function, passing in any needed arguments, you apply that function to the arguments. For example, given the following function: scala> def sum(a: Int, b: Int, c: Int) = a + b + c sum: (a: Int,b: Int,c: Int)Int You could apply the function sum to the arguments 1 , 2 , and 3 like this: scala> sum(1, 2, 3) res10: Int = 6 A partially applied function is an expression in which you don't supply all of the arguments needed by the function. Instead, you supply some, or none, of the needed arguments. For example, to create a partially applied function expression involving sum , in which you supply none of the three required 149