Using Closures in Java

In the last years, fuctional programming languages such as Haskel, F#, and clojure, have gained acceptance among programming enthusiasts. They allow a concise style of programming that is not easy to replicate with imperative languages.

Much of the power of functional programming languages is linked to the existence of closures. A closure is a way of binding variables to function definitions, so that you can refer to the variable later from the body of the function. The way the concept works is similar to fields in an object, but without requiring the existence of a class. This means that, in general, functions can have the same power of classes in an OO language.

For example, in common lisp one can write something like this:

(defun f ()
  (let ((x 0))
    (function (lambda ()
                (print (incf x))))))

(defvar add (f))
(funcall add)
(funcall add)

Here, we are creating a function f that returns a function (as defined by the lambda form). However, the returned function increments the value of x, which is a variable internal to the function f itself. Now, every time we call add, we are in fact incrementing and printing the value of x. Thus, the result of the execution of these lines is just

1
2

 
In this example, the function add has access to the internal variable x, defined in the let scope. Notice that, each time we call “add” we are incrementing that internal variable, even though the function f has ended — now, that is a trick!

Doing something like this is a non-functional language requires the help of OO. In Java, it gets a little ugly. In the following, I show how we can define a general interface for a unary function. This interface can be implemented so that some variables are bound, in a way similar to a closure.

import java.util.ArrayList;
import java.util.List;

public class Test
{
	interface UnaryFunc<T> {
		void exec(T t);
	}
	class ListIt<T> {
		List<T> l_;
		public ListIt(List<T> l) {
			l_ = l;
		}
		void apply(UnaryFunc<T> f) {
			for (T e : l_) {
				f.exec(e);
			}
		}
	}
	private UnaryFunc<Integer> getClosure(final int x) {
		final int[] total = {0};
		return new UnaryFunc<Integer>() {
			public void exec(Integer t)
			{
				total[0] += (t + x);
				System.out.println("x val: " + x  + " t: " + t + " total: " + total[0]);
			}};
	}

	protected void useClosure(UnaryFunc<Integer> f) {
		List<Integer> x = new ArrayList<Integer>();
		x.add(2);
		x.add(4);
		x.add(5);
		x.add(6);
		new ListIt<Integer>(x).apply(f);
	}

	protected void callClosureAcceptingMethod() {
		useClosure(getClosure(20));
	}

	public static void main(String []args) {
		Test t = new Test();
		t.callClosureAcceptingMethod();
		// print:
		// x val: 20 t: 2 total: 22
		// x val: 20 t: 4 total: 46
		// x val: 20 t: 5 total: 71
		// x val: 20 t: 6 total: 97
	}

}

What is going on here? The main action happens on method getClosure. The returned object is just the representation of a function. The variable total is being hold by the function object, and each time the function is executed, it adds the given value t. Also, notice that not only a local variable can be part of the closure, but also the parameter x, which is also added each time the function object is called.

Finally, notice that only a final variable can be used as part of the closure. This is a limitation of Java. For that reason, if we need a place to hold mutable data, we need to declare an array with one position (as we did with the total variable). It is a nuisense, but not really difficult to remember.

What about C#?

The current version of C# is much more friendly to users of closures. Moreover, the above example can be written much more easily — C# simplifies all that by using delegates, instead of requiring us to create a separate class just to hold the anonymous method. It also supports automatic type detection, which is another plus. But this is probably a good subject for a future post.

Similar Posts:

Similar Posts

13 Comments

  1. Wie gesagt hat München kein eigenes Casino zu
    bieten. Roulette und Black Jack wird man dort zwar nicht finden, aber eine
    Reihe von anderen Spielen. Wer eher am Automatenspiel interessiert ist, für den gibt es eine
    ganze Reihe von Spielotheken in München.
    Das Spiel Center München gilt als feste Größe unter den Spielhallen in der bayerischen Landeshauptstadt.
    Das Europlay Casino im Münchner Osten kombiniert modernes
    Automatenspiel mit klarer Struktur und gutem Service.
    Hier spielt man mit Systemen von Merkur, Bally Wulff und Novomatic.
    Besonders geschätzt werden die regelmäßigen Aktionen wie Bonuspunkte oder kleine Gewinnspiele, die den Aufenthalt abwechslungsreicher gestalten.

    References:
    https://online-spielhallen.de/dolly-casino-freispiele-alles-was-sie-wissen-mussen/

  2. Positiv fallen die zahlreichen Aktionen, regelmäßigen Freispiele und das starke Live-Casino auf.
    Freispiele haben üblicherweise einen ×30 Umsatz?Erfordernis, Bonusgeld meist ×40.
    Insgesamt bekommst du bis zu €1.200 + 220 Freispiele über
    die ersten 4 Deposits. Ich nutze meistens mein iPhone, und die mobile
    Version läuft schnell, sauber und ohne Ruckler – egal ob
    ich Slots oder Live-Spiele spiele. Ich spiele aktuell aktiv bei Verde Casino und der Einstieg ist fast schon verdächtig einfach.

    Diese Kombination aus Bonusgeld und Freispielen maximiert das Spielvergnügen und die
    Gewinnchancen. Diese relativ kurze Gültigkeitsdauer erfordert eine aktive Teilnahme und rechtzeitiges Freispielen. Die Gewinne
    aus diesen Freispielen werden dem Bonusguthaben hinzugefügt und unterliegen einer 40-fachen Umsatzanforderung.
    Jede Bonusstufe ist mit spezifischen Freispielen für verschiedene
    beliebte Slots gekoppelt, darunter Joker Stoker, Starburst und Book of Fallen.
    Verde Casino gehört zu den aufregendsten Online-Casinos,
    die eine beeindruckende Sammlung von Bonuscodes und Promo-Aktionen bieten. Online-Casinospiele sollen unterhalten und keine Sorgen über finanzielle Verluste auslösen.
    Um den dritten Einzahlungsbonus zu aktivieren, ist eine Einzahlung
    in Höhe von mindestens 10$ nötig. Auch dieser Bonus wird ab einer Mindesteinzahlung in Höhe von 15$ gutgeschrieben. Der erste Einzahlungsbonus kann ab einer Einzahlung von mindestens 10$
    in Anspruch genommen werden.

    References:
    https://online-spielhallen.de/starda-casino-promo-code-ihr-schlussel-zu-exklusiven-vorteilen/

  3. Zu den Grand Casino Basel Öffnungszeiten bieten nicht nur die Tisch- und Automatenspiele gelungene Unterhaltung.

    Es kommen durchaus immer wieder Spieler direkt vom nahegelegenen Flughafen, die eine Wartezeit überbrücken, indem
    sie im Casino Basel Erfahrungen sammeln. Ein solches Ausweisdokument ist
    auch erforderlich, um den Ausweis einzuscannen und zu überprüfen, ob eine Spielersperre
    vorliegt, durch die der Einlass ebenfalls
    ausgeschlossen wäre. Du kannst dich direkt vor Ort anmelden.
    Mit einer ESBK Konzession der Kategorie B und einem grossen Spielangebot bietet dieses Schweizer
    Kasino Besuchern beste Unterhaltung unter sicheren Gegebenheiten.
    Das riesige Bauwerk in Form eines grossen roten Würfels, das abends
    sogar noch stilvoll beleuchtet ist, bietet einfach deutlich mehr als „nur“ tolle Spiele mit
    hohen Gewinnchancen. Darüber hinaus gibt es auch noch weitere viele gute Glücksspielanbieter im Internet, die für Kunden aus der Schweiz
    geeignet sind. Das Stadt Casino Basel liegt
    keinen Kilometer von der Grenze zu Deutschland und Frankreich entfernt und ist daher auch aus diesen Ländern gut zu erreichen.
    Es ist unter dem Namen Golden Grand Online Casino geführt und bietet den Vorteil eines Bonus
    für Schweizer. Im Davos Casino beispielsweise konnte ich lediglich kleine Snacks und Getränke an der BAr zu
    mir nehmen.
    In Basel St.Johann, direkt am Flughafen und in nächster Nähe zur Grenze nach Frankreich,
    befindet sich die Spielbank Basel. Bonus und Freispiel Angebote ohne
    Einzahlung Eine Besonderheit ist das winddynamische Werk, welches vom eingebauten Spieltisch aus anspielbar
    ist. Die Silvesterkonzerte im Musiksaal werden seit 1996
    vom damals gegründeten Basler Festival Orchester gespielt.

    Die immense Schuldenlast durch das übernommene Sommercasino konnte jedoch nicht bewältigt werden und
    so wurde das Sommercasino samt Park 1937 verkauft. Da sich die
    Sommercasino-Gesellschaft sich in den folgenden Jahrzehnten zunehmend verschuldete, während das Stadtcasino erblühte, wurden 1907 die beiden Gesellschaften fusioniert.

    References:
    https://online-spielhallen.de/ihr-ultimativer-leitfaden-zu-sofort-casino-bonus-codes-wissenswertes-fur-spieler/

  4. Here are some of the most frequently asked questions about online
    casinos in Australia. Novice online casino players may not be familiar with the company known as eCOGRA,
    but experienced players normally regard it with great respect.
    The most common question new Australian gamblers ask is whether online casinos are legal in Australia.
    Almost half of all Australian players use mobile devices to play their favourite casino
    games these days.
    All the information about bonuses and promotions should be clearly stated, including details about wagering requirements
    and other terms and conditions. Those are just some of the questions that you
    need to ask yourself before deciding on which casino site to play.
    Almost every casino these days has some sort of a welcome promotion for their new customers,
    and so do all the Australian casinos on our lists.
    Speaking of pokies, there are literally thousands of titles to pick from, and a casino site should give you a fair range of choice.
    Maybe you’re only interested in online pokies, but what if you want to
    relax with some old-fashioned roulette from time to time.

    Here are some of the most important things we
    look for in top Australian casino sites.Security
    is by far the most important aspect of any casino site.

    Once you lose a certain amount of money at an online casino, you
    get a percentage of it back in bonus funds. Reload bonus is
    not really a type of bonus fund but rather a group of bonuses that are meant
    for existing players. It’s time for something a
    little bit more exciting – bonuses at AU casinos online.
    I’m personally not a big fan of these, to be honest,
    but the number of players logging bets onto them at every casino website says they are nearly as popular as table games.
    Many of the top gambling sites in Australia now have a fully gamified system with challenges and quests that you can complete to earn real money prizes.

  5. It’s similar to Sicilian chicken, with the exception of the sun-dried tomatoes.
    With this phenomenal dish, you’ll always say, “I do… want a second serving.” This simplified version of classic chicken parm has all the same
    amazing flavors.
    Take a dip in the Coral Wing Pool, perfect for lounging and soaking up warm rays in the heart of Parañaque City.
    Head to the Retreat Spa Pool, inspired by Mediterranean architecture, for a peaceful and rejuvenating experience.

    If unwinding by the water sounds like your perfect escape, Okada Manila has three stunning
    pools that cater to different moods. This experience takes you through the resort’s attractions, ending with a
    relaxing foot massage at The Sole Retreat.

    References:
    https://blackcoin.co/58_online-cashback-casino-play-live-casino-games-at-lucky-vip_rewrite_1/

  6. Read, write, and copy speeds are dozens of MB/s ahead
    of the other HDDs on this list, and understandably,
    this drive ends up scoring the best overall.
    The downside is that this isn’t a very portable drive, owing to it
    needing to be plugged into an external power source like a wall outlet or
    a portable battery. Those capacities also come at a very low price-per-terabyte, making this ideal for housing massive video and
    other media files in addition to system image files.
    The FireCuda external game drive is exactly the kind of
    thing you need in a case like this. Copying files internally is incredibly fast on this drive, second
    only to the Seagate Expansion, but copying to this drive is significantly slower in my testing.

    Despite these limitations, its fast read speeds,
    three-year warranty, and portability make it an excellent choice for those requiring no more than 2TB.

    However, its limited capacity options, with a maximum of 2TB, and a high price per terabyte are significant drawbacks.
    While it doesn’t excel in any single aspect, its balanced performance, decent capacity, and portability without significant drawbacks make it
    the best overall option for most users, offering a well-rounded package at a
    reasonable price.

    References:
    https://blackcoin.co/lucky-hunter-casino-a-comprehensive-review/

  7. Register today, claim your bonus, and level up your gaming experience —
    where every spin brings you closer to a win! It delivers
    push notifications, optimized performance, and instant access to the
    casino — perfect for gaming on the go. The platform uses SSL encryption to protect personal data and payments, providing a completely secure gaming environment.
    LevelUp Casino is a fully licensed online casino, operating under international gaming regulations to ensure
    fairness and transparency.
    These updates reflect our dedication to providing convenient, secure transactions for all players.

    Our mobile optimisation improvements ensure seamless gameplay across iOS
    and Android devices. Progressive jackpot wins dominated the leaderboard, with several Australian players securing five-figure payouts.
    We’ve expanded our gaming library with fresh titles from premier providers including
    NetEnt, Microgaming, and Pragmatic Play. Players should review bonus terms before claiming any promotional offers to understand withdrawal conditions.

    The platform scores well across key performance metrics
    that matter most to players. The Level Up Casino community provides detailed feedback about platform
    performance and gaming experiences. Players appreciate the variety of payment methods including traditional cards and
    cryptocurrency options.

  8. To do this, you must enter that 9-digit code in the “Another workstation” section. When you do this, you will see that a 9-digit code appearing
    on the left side of the screen. Its primary purpose
    is to grant bidirectional remote access between personal computers and mobile devices.

    AnyDesk is a free-to-use program for PCs that allows you to access another computer remotely
    and securely.
    This approach can be extended to other geospatial challenges, such as wildfire risk assessment or transportation planning.
    By integrating spatial data clustering and interactive visualization, it enhances disaster
    response planning and urban risk management
    strategies. H3 can significantly improve flood response efforts by
    integrating various data sources including flood zone maps, population density, building infrastructure, and real-time water level
    readings.
    This can be useful when you need to partition the data.
    It’s a simple point in polygon problem. Share insights, grow your
    voice, and inspire the data community.

    References:
    https://blackcoin.co/australian-no-deposit-bonus-codes/

  9. The hotels on the property have a combined 1,171 rooms.
    The casino, which was Queensland’s first, is situated next to the Nerang River and is operated by Star Entertainment Group.
    The Star Gold Coast (formerly Jupiters Hotel and
    Casino) is an integrated resort located in the suburb
    of Broadbeach on the Gold Coast in Queensland, Australia.

    Will you live it up in one of our executive rooms, soak up
    the sun on your own personal balcony in one of our club
    suites, or live like royalty in one of our two penthouses?
    Set amid one of the longest strips of pristine beach in the world and
    surrounded by lush hinterland ranges, Conrad Jupiters, on the Gold Coast, is the ideal location for one
    of Australia’s best hotels. You can also enjoy movie nights,
    live music, comedy, big screen sports and more.

    In 2008, security staff at the casino and other venues took
    part in a trial of head mounted cameras which were
    worn over the ear. Between 1993 and 2001,
    the casino was defrauded of $5.7 million when corrupt casino staff and food suppliers fabricated food orders and invoices.

    Jupiters Hotel & Casino made headlines in 1995 when then Brisbane Broncos
    Rugby League player Julian O’Neill urinated on the carpet under a black jack table on two separate occasions.
    In 2011 it became part of Echo Entertainment Group when Tabcorp listed its casino assets.
    The resort is connected to the adjacent Gold Coast Convention and Exhibition Centre.

    A short drive up the coast from Golden Riviera Beach Resort and you will find the
    entertainment venue of Jupiters Casino. The Star Casino also plays host to a range of entertainment shows throughout the year, with some
    of the biggest names in entertainment choosing to perform here.
    With seven amazing restaurants; serving cuisines from
    Italian to Chinese, there is something for every taste.

    The Gold Coast has several unique night-time attractions and
    destinations you’ll love to visit with a partner or a group of friends.

    The reason for this is simply that it takes time for an article to be cited by other articles.

    References:
    https://blackcoin.co/winspirit-casino-login-australia-quick-access-to-premium-gaming/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.