Scala Functional Literal

0

In this article, I will briefly introduce you to functional literals.

So what is a functional literal?

It is a function without a name also called anonymous function. You can pass it around as a parameter to a method, or assign it to a variable. I will show you an example of each case.

Example of Functional Literal

In this example, we are simply converting string “function” to upper case and then print it.

We have called map on the string “function”. A functional literal is passed to map to convert each character to its uppercase. The result is String again so we call onforeach to print each character.

For now, don’t worry much about map method, think of it as a method which iterates over each element of the collection and applies the algorithm passed in.

FunctionalLiterals:

object FunctionalLiterals {
  "function".map(s=>s.toUpper).foreach(print)
  
  def main(args: Array[String]): Unit = {    
  }
}

Output:

FUNCTION

Functional Literal Syntax

Now since we have already seen how a functional literal is used. Let’s look into its syntax.
s is a String parameter,  next we see a right arrow indicating the start of function, and then comes the body of the function.

s=>s.toUpper

If you notice s is not declared with any type. This is because the Scala compiler can infer from the expression that s is Char.
We can also define the above function with the parameter type as (param:type). For example:

"function".map((s:Char)=>s.toUpper).foreach(print)

We will now introduce another parameter to the function and this time we will assign it to a variable.

FunctionalLiterals

object FunctionalLiterals {
  "function".map(s=>s.toUpper).foreach(print)
  "\nLiterals".map((s:Char)=>s.toUpper).foreach(print)
  println
  val prefixStr = (prefix: Int, s:String) => prefix + s;
  println(prefixStr(1, " as variable"))
  
  def main(args: Array[String]): Unit = {    
  }
}

Output:

FUNCTION
LITERALS
1 as variable

Note that the list of parameters must be declared within the parenthesis else the interpreter will throw error.

Download source code

In this article, I have introduced you to functional literals. You can download the source code here: functionLiteralExample

Share.

Comments are closed.