05: Coding Scala Way – FP concepts

Example #13: Explain the concepts

Can you explain the Scala concepts applied in the following code snippets?

Output:

1. Higher Order Functions: Line 12” is a higher order function as the function not only takes a function as an argument i.e. f: T => R, but also returns another function i.e. List[T] => List[R] via l => l.map(f).

Line 23” is a higher order function as the function takes another function as an input argument i.e. T => R.

map, flatMap, filter, etc are higher order functions as they take functions as arguments.

2. Closures: Line 12” is a closure as it closes over a “list”. The list is supplied in “Line 26” aClosure(input) //pass the list to the closure.

3. Generics: C[_], T, R, and C[T] are Scala generic type parameters. For example, C[T] can be substituted for List[Int] and can take List(1, 2, 3) & C[_] is a higher kinded type that can be substituted for List[List[Int]], List[Option[String]], List[List[List[String]]], etc.

4. Implicits: are used where the compiler rewrites

TO:

The magic happens due to implicit invocations. The ” List(1, 2, 3) anotherFunction {x => x + 1}” invokes the function on “Line 23” inside the “AnyRef” object on “Line 20”, which takes “(input: C[T])” as an argument. “C[T]” can be substituted for the “List[Int]”. Similarly, “implicit wrap: Wrapper[C]” on line 23 invokes “aFunction” via ListWrapper on Line 10, which is of type Wrapper..

5. Partial functions: Line 25” is a partial function.

How will you rewrite the above code without implicits?

Output:

What is the benefit of the above code?

You could have just called a list class’s “map” function as in

Firstly to demonstrate the Scala concepts with a simple example.

Secondly, the above code can be extended to be an abstraction (i.e. a functor) and handle other C[_] types like “Option[T]” as shown below:

The Output: will be

Q. What if you want to use Some(5) & None instead of “Option”?
A. You can define two functions that returns a type Option.

Pay attention to: lines 45 & 47 where new functions were added to handle Some(x) and None respectively via functions. Lines 39 to 42 make use of these functions.

Output:

Popular posts:



300+ Java & Big Data Interview FAQs

800+ Java Interview Q&As

Java & Big Data Tutorials

Top