First Class Functions in Scala

One of the core values of functional programming is that functions should be first-class.The term indicates that they are not only declared and invoked but can be used in every segment of the language as just another data type. A first-class function may, as with other data types, be created in literal form without ever having been assigned an identifier; be stored in a container such as a value, variable, or data structure; and be used as a parameter to another function or used as the return value from another function.

Function literals are anonymous , they don’t have a name by default, but we can give them a name by binding them to a variable. A function literal is defined like so:

(x:Int) => x * 2 // Function Literal
val double = (x:Int) => x * 2 //Assigned function to the variable double

package com.scala.test

object Anonymous {
def main(args: Array[String]) {
val x = List.range(1, 10)
val evens = x.filter((i: Int) => i % 2 == 0) // (i: Int) => i % 2 is the function literal
println(evens)
val double = (x:Int) => x * 2 // assigned the function literal to variable double
println(double(5))
}

}

Output
List(2, 4, 6, 8)
10

Functions that accept other functions as parameters and/or use functions as return values are known as higher-order functions.

Leave a Reply

Your email address will not be published. Required fields are marked *