05: Coding Scala Way – FP concepts

Example #13: Explain the concepts

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

1. Higher Order Functions: Line 10” is a higher order function as the function returns another function i.e. List[T] => List[R] is returned.

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

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

2. Closures: Line 10” is a closure as it closes over a “list”. The list is supplied in “Line 23” 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).

4. Implicits: The output of the above code is:

The magic happens due to implicit invocations. The ” List(1, 2, 3) anotherFunction (x => x + 1)” invokes the function on “Line 20” inside the “AnyRef” object on “Line 17”, which takes “(input: C[T])” as an argument. “C[T]” can be substituted for the “List[Int]”.

5. Partial functions: Line 20” is a partial function, which takes a custom list of type “AList”

Due to implicits, it gets substituted to “Line 8” object of type “MyList”, and invokes its function “aList”.

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 44 & 46 where new functions were added to handle Some(x) and None respectively via functions. Lines 38 to 42 make use of these functions.


800+ Java Interview Q&As Menu