An excellent explanation on Scala Methods and Functions:
Apparently, Methods in Scala are different from Functions. From what I understand, a method is similar to a method in Java – it takes input and produces an output. But a Function is an object. Also takes an input and produces an output, but is an object. Here’s how they’re different:
def f1(x:Int):Int = x*2 //Method that doubles input
def f2 = (x:Int)=>x*2 //Function that doubles input
//f1.toString //Cannot be done!
f2.toString //Is perfectly valid
For more details, I’d suggest you take a look at Jim McBeath’s explanation.
In this part, we take functions a little further and discuss the following:
- Working with Lists of Functions
- Generated Functions
This builds a bit on the previous post on Functions in Scala, so if you haven’t seen it already, I’d highly suggest you take a look here: Working with Functions in Scala – Part 1
Scala treats functions as first class citizens. I keep forgetting the syntax for it, so putting it here as a handy reference. This post deals with the following features of Scala:
- Anonymous Functions
- Assigning Functions to variables
- Composite Functions
Please note that the term ‘function’ here is used to refer to both mathematical functions and programmatic functions. The key strength of Functional Programming languages is the ability to unify both.