Scala functional programming: Functions as first class citizens

Learn
2 min readJan 3, 2022

What is the first thing you need to do functional programming?
Functions.

Functions need to be available as first-class citizens in the programmer’s toolkit. A method in java can appear to be a function but it is not. A method is associated to the class. If another class needs to do call this java function/method, it needs to also know the class where the method is. That is to say Java does not support functions as first class citizens.

In Scala, you can define a function as a variable. For example, a function that triples a number passed in would be defined as follows.

val triple = (x : Int) => 3 * x
val result = triple(10)
println(result)

triple is a function and you can define it just as easily as you define an integer.

val age:Int = 34

Invoking functions
One thing that is special about functions when compared to say Strings is that the functions can be invoked. Invocation is applicable only for functions and not for Strings/Ints. Invocation syntax as below.

println(doubler(10))
20

Treating functions as first class citizens

Functions can be looked at in the same plane as Ints or Strings. This realization would enable you to use functions with much more power than the traditional approach of viewing methods just from a perspective of invoking/executing them.

A function can be assigned to a variable just like a String can be assigned to a variable

val name:String
= "A string in scala"
val doubler:Int => Int
= x =>2*x

A function can be dereferenced from a variable just like a String can be dereferenced from a variable

val name:String
= "A string in scala"
val doubler:Int => Int
= x =>2*x
println(name)
println(doubler(10))

A function can be returned from a function/method just like a String can be returned from a function/method

val getName: Int => String = (n : Int) =>  
"A string value"
val times: (Int) => Int => Int = (n :Int) => {
n match {
case 2 => doubler
case 3 => tripler
}
}

This ability to treat functions as first class citizens to the same extent as treating Strings as first class citizens would extend to pretty much everything from a Scala language perspective. Of course, it is on the programmer to put this capability to creative use based on paradigms that are available in the functional programming world.

--

--