Skip to content

Closures

Posted on:August 21, 2023 at 01:13 PM

Hey folks, welcome back! Today, we’re about to embark on a journey into the enchanting realm of closures. Don’t be alarmed if the word “closure” sounds a bit mysterious – we’re here to unravel its secrets together. So buckle up as we delve into this intriguing concept, sprinkled with a dash of humor, humility, and excitement.

Table of contents

Open Table of contents

Sections

Defining the Enigma: Closures!

Picture this: You’re a function, and you’re hanging out in a neighborhood of code. Suddenly, you spot some free variables – identifiers that you didn’t define but could totally relate to. That, my friends, is the essence of a closure! In simpler terms, a closure is a function that cozies up to those free variables in its surroundings, in a way that only it can understand. And when I say “surroundings,” I’m talking about the lexical context, a fancy term for the scope that sets the boundaries of variable access. Neil Gafter, a real wizard in the world of programming, once shared this captivating definition of closures. Trust me, he knows his stuff!

Hold On, What’s in a Function?

In mathematics, referential transparency is a property of expressions that can be replaced by equivalent expressions without affecting the result. For instance, you can replace the sub-expression “2 multiplied by 4” with “8” or even “2 multiplied by 2.” The result remains the same. This mathematical property is akin to the concept we encounter in functional programming.

Lexical Scope: Where the Magic Happens

Now, imagine a scene where each variable is a star, and each block of code is a different galaxy. Lexical scope is like the rulebook that says, “Hey, star, you can only twinkle in this galaxy!” In other words, it defines where a variable can be seen and used. So when a closure comes along, it’s like that friendly astronomer who follows the rulebook, making sure each star knows where it can shine.

Lambda Expressions and Their Peculiar Demands

Alright, let’s break out the coding potions and conjure up a closure using a lambda expression. We’ll create a magical interface called “Task.” This interface is a bit quirky – it insists that the value it works with should be final or effectively final (yeah, no changing your mind, buddy!).

@FunctionalInterface
interface Task {
    void doTask(int value);
}

public class ClosureAdventures {
    public static void main(String[] args) {
        int val = 111;

        Task task = value -> {
            System.out.println(value);
            System.out.println("Task completed!");
        };

        unleashTheClosure(task, val);
    }

    static void unleashTheClosure(Task task, int value) {
        task.doTask(value);
    }
}

Peek-a-Boo Closure Magic!

Did you see that? We’ve brewed a lambda potion and created a magical interface “Task.” We conjured a lambda that can only work with “final or effectively final” values. And guess what? When we invoke the lambda, we’re not in the same scope as when we created it. But fear not, intrepid adventurers! The JVM is like a mystical guardian, carrying that value with the closure, making sure it never feels lonely.

Why Closures Are Your Programming BFFs

Closures might seem like the wise wizards in your code realm, and for good reason. They’re the glue that binds free variables to functions, allowing them to work their charm across scopes. Closures also play matchmaker between sibling functions, sharing variables in their cosmic neighborhood. This control over scope and sharing is what makes closures a precious gem in the programming treasure chest.

Conclusion:

So, fellow explorers, as we bid adieu to this whirlwind tour of closures, remember this: Closures are like code’s secret agents, carrying the essence of variables from one scope to another. They’re like the trustworthy messengers that ensure your functions work seamlessly and make the galaxy of programming a more connected and enchanting place. Until next time, keep coding, keep exploring, and keep embracing the magic of closures!🌟

You can find the repo for this section of the course Here