Free Trial

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

Share this Page URL
Help

Section A.3. Collections - Pg. 380

380 APPENDIX A Introduction to Scala A.2.4 Functions With the blend of object oriented and functional styles, Scala sports the concept of general functions. That is to say, a specific instance of a function can be passed around and is in and of itself a specific type. Functions are first-class values in Scala, which essentially means that you can create generic functions that take A and return B . Such a relationship is typically expressed as A => B and is referred to as a lambda function. Consider the following example: scala> val f = (s: String) => s.toLowerCase f: (String) => java.lang.String = <function1> scala> f("SOMeThInG") res8: java.lang.String = something Here, a function that takes a String and returns a String is assigned as the value f and has the type Function1 . With this function defined, it's possible to pass a single argument to f and treat the value function like you would any other method; the only difference being that the function is itself an instance rather than being contained within a class. In essence, this is the basis of all functional programming within Scala: functions can be any type to any type, and functions can even take other functions as arguments, resulting in what are known as higher-order functions. Functions themselves can have