def plus1(a : Int) : Int = 1 + a
it takes an argument
1 + a(you guessed it). you can call this function like
plus1(2). [you could have enclosed the body of the function in curly braces, but it's just one expression, so you don't have to]
so, now let's define a higher-order function. that's a function which takes another function as parameter or returns a function.
def doWithInt(a : Int, f : Int => Int) : Int = f(a)
this is a function that takes an
Intas first parameter and a function type as second. the parameter
fis a function of type
Int => Intwhich takes an
Intas parameter and returns an
Int. this function simply applies the function
fto the parameter
a. you could call this function passing to it a reference to the function
doWithInt(3, plus1). this will return
4as it applies
so, these are just the basics of functional programming with scala. things can become quite weird when it comes to more complex higher-order functions, e.g. function returning functions, currying or recursion. have a look at 'Scala By Example' for examples.
one thing i forgot to mentioned is some syntactic sugar for the example above. instead of calling
doWithInt(3, plus1)you could have equally done
doWithInt(3, 1 +)
this is because
+is a member function of the type
Int, as seen in a previous post.
so, that's it for this post then. more on functional programming with scala coming soon.