More on Functions in Scala
In this article, we shall see about two concepts:
- Lambda Functions (Anonymous Functions)
- Higher-order Functions
As already mentioned, Scala supports both object-oriented and functional programming. This article covers a bit of functional programming concepts.
All functions in Scala are values, just like any other String
or Int
.
Lambda (Anonymous) Functions
Anonymous functions are functions that do not have a name. They are used to help keep code concise and readable.
You might already be using lambda functions without knowing about them.
val items = Seq(1, 2, 3, 4);val even = items.filter(x => x % 2 == 0); // x => x % 2 == 0 is our lambda function.
In the above example, we are passing a nameless function with one parameter
x
which checks whether x % 2
is 0 and returns true or false.
This nameless function is a lambda.
What is its use? Exactly what you see. They are used in places where you need to pass a function as a parameter.
By the way, functions that accept these anonymous functions as parameters are higher-order functions.
Higher-order Functions
These functions either accept other functions as parameters or return a function as a result.
Here's an example:
def DoubleThis(fn: T => Boolean): Int
Here, T
is a generic type inferred from the value of p
supplied.
Since this function accepts a function p
as a parameter, it is a HOF.
Example:
def TrueOrFalse(n: Int): Boolean = { return if(n < 0) false else true;}def RunThisFunctionOnOne(fn: Int => Boolean) = { val result = fn(1); if(result == true) println("This is true"); else println("This is false");}RunThisFunctionOnOne(TrueOrFalse);
In this example, we are passing the TrueOrFalse
function as a parameter
to RunThisFunctionOnOne
.
Let us see an example with a lambda.
def RunThisFunctionOnOne(fn: Int => Boolean) = { val result = fn(1); if(result == true) println("This is true"); else println("This is false")}RunThisFunctionOnOne(n => if(n < 0) false else true);
Common examples of HOFs you'd use commonly are methods like filter
, find
,
map
, foreach
, etc., that are found on collections.
Function Types
Let us look into how function types are defined.
val addTwoItems: (Int, Int) => Int = (a, b) => a + b;
Here, (Int, Int)
is a list of parameter types.
=> Int
says that the function will return another
integer.
= (a, b) => a + b
is the actual lambda function.
Implicits & Givens
Scala provides givens
(implicit
in Scala 2)