Local Functions

If you understand the Scala function, the local function should be the most simple idea among all other Scala functional concepts.
When we use an Object Oriented approach, it is quite common to create private methods. They are a kind of helper methods, and we make them private because we do not want them to expose to the external world.
Scala offers the same notion using the local functions. You can define functions inside other functions. That's what we call as a Local Function. The local functions are visible only in their enclosing block.
Here is an example.

    import scala.io.Source
    import scala.io.Source._
    def getErrors(fileName: String) = {
        def isError(line :String) = {
            if (line.contains("[error]")) true else false
        val f = Source.fromFile(fileName)
        for (l <- f.getLines() if isError(l)) yield l  
    getErrors("error_log") foreach println              

The getErrors function takes a file name as input, and it returns the error messages. We are using isError as a local Function. Sometimes, people also refer them as Nested Function. The choice is yours, call them Nested or Local, but they are the same thing.
We learned about the function literals in the earlier post. The notion of a local function and the function literals works hand in hand in functional programming. They are the key element of a Higher Order functions that return a function.
Continue reading, and I will cover Higher Order functions in great depth.

Read More

Basics of Scala functions | Function Literals in Scala | Function values | Local Functions | Variable length argument | Default values and named arguments | Scala Placeholder syntax | Higher Order functions | Partially applied functions | Function currying

By Prashant Pandey -

You will also like:

Kafka Core Concepts

Learn Apache Kafka core concepts and build a solid foundation on Apache Kafka.

Learning Journal

Hadoop Security

Hadoop security implementation using Kerberos.

Learning Journal

Functional Programming

What is Functional Programming and why it is important?

Learning Journal

Lazy Evaluations

Evaluate the expression now vs evaluate it for the first use. Strict vs Lazy?

Learning Journal

Scala Variable length arguments

How do you create a variable length argument in Scala? Why would you need it?

Learning Journal