One Thing Scala: Two — Function standard language feature in Scala

Learn
2 min readJun 12, 2021

--

Scala has standard library support for functions. So you can import function and use the function to create your functions that you need to define for solving your business problem.

For example, say you had to write a function “twice” that doubles the input passed. Now you need to think about how many parameters your function would take, what kind of parameters it would take, what is the kind of return value for the function. Function “twice” would take one Int parameter and return one Int value.

Now, you need to figure out how to define such a function in scala. Scala has Function1, Function2.. Function22 where the number suffix indicates how many parameters the particular function takes. Here, we have only one parameter, so we need to choose Function1.

Functions in scala are generic which means you have the flexibility to define what type of argument your function takes and what type of return value your function returns. Let us say “Twice” takes an “Int” type argument and returns an “Int” type result.

So far we are thinking about how to specify the type specification of our “Twice” function. We still need to define the implementation portion.

val twice:Function1[Int,Int] = TBD

Now, we need to provide the actual definition for the function. The definition syntax has two portions — LHS with the parameter declarations and the RHS with the computation.

(x:Int) => 2 * x

So the complete definition of the “twice” function would be as follows

val twice:Function1[Int,Int] = (x:Int) => 2 * x

--

--

Learn
Learn

Written by Learn

On a continuing learning journey..

No responses yet